Reputation: 15683
I know it's naive question, but regex is always confusing for me.
I want to replace numbers in a string if they are between a tag, here parenthesis.
$str = " Some text 11 have number 12 (11,12,13)";
$array = array( 1 => 'one', 2 => 'two', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen');
foreach ($array as $key => $value) {
$str = preg_replace( 'regex to match $key', $value, $str);
}
The result should be
$str = " Some text 11 have number 12 (eleven,twelve,thirteen)";
I am struggling with regex pattern to match number which should be within parenthesis. Inside the parenthesis is only numbers and ,
.
Upvotes: 0
Views: 773
Reputation: 14941
You can try this:
$str = " Some text 11 have number 12 (11,12,13)";
$array = array( 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen');
foreach ($array as $key => $value) {
$str = preg_replace('/(\(|,)' . $key . '(\)|,)/', "$1" . $value . "$2", $str);
}
And when you var_dump($str)
:
string(53) " Some text 11 have number 12 (eleven,twelve,thirteen)"
Upvotes: 2
Reputation: 627100
I suggest using a regex that finds all consecutive numbers (digit chunks) separated with a comma after an opening (
. Then, the matches can be passed to a preg_replace_callback
and if the corresponding key is present in the array, replace it with the corresponding value, else, just put the match back.
Here is the regex:
(?:\G(?!\A)|\(),?\K\d+
See regex demo
Details:
(?:\G(?!\A)|\()
- Matches either the position of the previous successful match (\G(?!\A)
) or a (
symbol,?
- an optional (1 or 0) comma\K
- an operator discarding all the text matched so far\d+
- 1 or more digits (the only text we have in the match returned).And here is the PHP code:
$re = '/(?:\G(?!\A)|\(),?\K\d+/';
$str = "Some text 11 have number 12 (9,11,12,13)";
$array = array( 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen');
echo $result = preg_replace_callback($re, function ($m) use ($array) {
return !empty($array[$m[0]]) ? $array[$m[0]] : $m[0];
}, $str) . PHP_EOL;
The result is Some text 11 have number 12 (9,eleven,twelve,thirteen)
as 9
is missing in the $array
.
Upvotes: 4
Reputation: 23880
I'd use preg_replace_callback
. Then you can use \(([\d\h,]+)\)
which checks for numbers, horizontal spaces, or commas inside ()
and captures all found values. The function then uses str_replace
to replace them.
$string = " Some text 11 have number 12 (11,12,13)";
$array = array( 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen');
echo preg_replace_callback('/\(([\d\h,]+)\)/', function ($matches) use ($array) {
return str_replace(array_keys($array), array_values($array), $matches[1]);
}, $string);
Demo: https://eval.in/589888
Upvotes: 2