phppreg-replaceposix-ere

convert ereg_replace to preg_replace in php


i have the following ereg_replace statement:

ereg_replace ( ".*alternative0=\"[^\"]*\"[ ]{0,10}>", "", $v );

since ereg_replace is deprecated I would like to upgrade it to preg_replace and I also want to upgrade my code so only the first occurrence will be replaced.

preg_replace ("/.*alternative0=\".*?\".*>/", "", $v,1 );

but it seems to work partially.

the major problem is that when I have whitespace between the " and > my preg does not work

here are some example strings i want to to change:

<tag type="head" alternative0="not head">{!head!}</tag>
<tag type="tail" alternative0="tail>{!not tail!}</tag>

but it also may be:

<tag type="head" alternative0="not head">{!
xxxx   !}</tag>

or even:

<tag type="header" alternative0="not head "    > {!  blah bla !}</tag>

Solution

  • You will have a more efficient pattern with this:

    preg_replace ('/.*alternative0="[^"]++"[^>]*+>/', "", $v, 1);
    

    You can't use something like: .*> because the dot match all characters and the quantifier * is greedy thus the .* match the final > too and the > from the pattern is never matched or not matched at the good offset.