RWS RWS - 6 months ago 8
PHP Question

preg_replace does not replace the value as required

Assume we have a php array $row_mid, which contains strings like 'reaction_l0', 'reaction_l1', 'reaction_r0', 'reaction_r1' (in each case the number goes from 0 to 4. These strings are enclosed by

<div>
tags. I want to run a loop and remove these strings with preg_replace ():

$i = 0;
while ($i < count ($row_mid)){
$row_mid [$i] = preg_replace ("~^reaction_.[0-9]$~", "", $row_mid [$i]);
$i++;
}


The regexp ^reaction_.[0-9]$ was developed with the help of https://regex101.com/ and tested successfully with strings
<div>reaction_r1</div>
(no match, I need the tags stay where they are) and
reaction_r1
(match). It doesn't work, however.

Answer

Get rid of the anchors, because they only allow the regexp to match the entire string, not when it's enclosed in tags.

$row_mid [$i] = preg_replace ("~reaction_.[0-9]~", "", $row_mid [$i]);
Comments