All All - 1 year ago 113
PHP Question

Regex for PHP preg_replace to find numbers between tags

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

Answer Source

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:


See regex demo


  • (?:\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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download