0

I can get along with regex when needed, but for some reason I am in the dark trying to figure out why preg_replace cuts off leading digit or space.

Example:

$phone = '00 385 1234567';
$sig = 'abcd <span id="phone"></span> efgh';
$text = preg_replace('/(<span[^>]*id="phone".*)(.*?)(<\/span>)/smi', '$1'.$phone.'$3', $sig);

echo $text;

First 0 is missing in result, also if there is any digit or space (or maybe some other sign as well), but not if first is a character or sign + and others. Can someone shed some light on this behaviour please?

hpet
  • 299
  • 1
  • 14
  • Your pattern is a bit "clumsy", since the second group is not matching anything. The current regex can be written as `'/(]*id="phone".*)()/si'` and in the replacement you would replace `$3` with `$2`. But to fix the current issue, replace `$1` with `${1}`. – Wiktor Stribiżew Oct 24 '18 at 07:45
  • uf, curly braces fixed my current issue. I need to check out what curly braces are all about :) thanks! ...I know it is a but clumsy, but it worked so far. Will check out your's and improve :) The second group is not matching anything in this example, but can be nothing or anything in real case. Please post your comment as answer. Thank you! – hpet Oct 24 '18 at 08:02
  • It is a duplicate and I closed the question. Note that your Group 2 will **never** match any text because `.*` before it will grab all the text it can and there will be nothing left for `(.*?)`. – Wiktor Stribiżew Oct 24 '18 at 08:04
  • Oh, I get it now. Thanks! Will correct. – hpet Oct 24 '18 at 08:11

0 Answers0