请参见代码中的注释。使用
\b
匹配
word boundary
并防止类似
XXH12345
不匹配。
$a = [
"This is one with H11111",
"This is one that has an H22222 in it",
"Tricky one WITH22222 in it",
"This is another H11111, like the first one",
"Here's a line without any number at all",
"Here goes H33333",
"H22222, finally."
];
foreach ($a as $key => $element) {
// Find any string matching H<digits> pattern
if (preg_match('#\bH\d+\b#', $element, $numbers)) {
$number = $numbers[0]; // Remember first found pattern
if (!isset($keys[$number])) { // Do we know this from before?
$keys[$number] = $key; // No, remember the index of this number
}
else {
$a[$keys[$number]] .= " + " . $element; // Yes, append to existing value
unset($a[$key]); // Then remove the appended element
}
}
}
print_r($a);
输出:
Array
(
[0] => This is one with H11111 + This is another H11111, like the first one
[1] => This is one that has an H22222 in it + H22222, finally.
[2] => Tricky one WITH22222 in it
[4] => Here's a line without any number at all
[5] => Here goes H33333
)