phpregexpreg-replace

Replace Javascript concatenation expression in a string with <em> tag


this is my first question here. I need to do what I guess is a simple php preg_replace() replacement but I have no knowledge about regular expressions.

I have an html formated text string, breaked by several " + figure("br") + " (including both begin and end quotes). I need to change them to <em class="br"></em> where 'br' is the argument I must preserve.

I have about 200+ text to replace. Of course I could replace the pre and post separately, but want to do it in the right way. Thanks in advance and forgive my English.

Sample input: <p>Bien!</p> <p>Gana <b>Material</b> por el <b>Doble Ataque</b> al " + figure("bn") + "c6 y a la " + figure("br") + "h8.</p>

Sample output: <p>Bien!</p><p>Gana <b>Material</b> por el <b>Doble Ataque</b> al <em class="bn"></em>c6 y a la <em class="br"></em>h8.</p>

[Edited for including the real data]


Solution

  • If you have a variable pre and post string (or one with meta characters as in your case), then I think it's best to use some regex escaping there:

    //  " + figure("br") + "
    $pre = '" + figure';
    $post = ' + "';
    
    // escape
    $pre = preg_quote($pre, "#");
    $post = preg_quote($post, "#");
    
    // then the regex becomes easy
    $string = preg_replace(
                   "#$pre\(\"(\w+)\"\)$post#",
                   '<em class="$1"></em>',
                   $string
    );
    

    I assume you are converting some source code?