PHP preg_replace escape ampersand in backreference regex

959

Ok, I've checked and looked, but today my SearchFU is not strong. I am encountering an error with backreferences in some Regexpreg_replace('~$\s*<div>([^<]*?)</div>$\s*~me', '\1', $source); I could really use a hand with. The expression finds<div> tags and returns just the content removing the tag and enclosing linefeeds. ie:

<td>
        <div>some value</div>
    </td>

becomes

<td>some value</td>

Everything works fine until<div>&nbsp;</div> which causes:

Parse error: syntax error, unexpected '&' in D:\wamp\www\processfile.php(18)
: regexp code on line 1 Call Stack: 0.0010 143600 1. {main}()
D:\wamp\www\processfile.php:0 0.0350 170328 2. preg_replace()
D:\wamp\www\processfile.php:18 Fatal error: preg_replace(): Failed evaluating 
code:   in D:\wamp\www\processfile.php on line 18 Call Stack: 0.0010 143600
1. {main}() D:\wamp\www\processfile.php:0 0.0350 170328 2. preg_replace()
D:\wamp\www\processfile.php:18

If I remove the \1 backreference, the expression will happily erase all the content in the div tags, but seems to want to parse it as a new expression.

Is there a way around this, or should I just pre-process the &'s before this line gets executed?

956

Answer

Solution:

It's thee modifier at the end of your regex. It causes the replacement to beeval()'ed. Remove it:

preg_replace('~$\s*<div>([^<]*?)</div>$\s*~m', '\1', $source);

See the PHP docs for PCRE pattern modifiers.

People are also looking for solutions to the problem: php - Why does the "echo" statement support outputting multiple arguments in a single line and the "echo" function does not?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.