1

I need replace image tags with smiles to {smile:smilename}

   <?php
    $pattern = '<img src="/img/smile/(.*?).gif">';
    $replacement = '{smile:$1}';
    $subject = '<div contenteditable="true" id="message_text">text<img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"></div>';
    echo preg_replace($pattern, $replacement, $subject, -1 );
    ?>

I get:

<div contenteditable="true" id="message_text">text<{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}></div> 
  • <{smile:smile3}>

but i need

  • {smile:smile3}
1
  • You should parse the HTML first and then manipulate the src attributes of img elements. You're trying to parse HTML with regex, and that's not a good idea. Commented Aug 21, 2013 at 13:51

2 Answers 2

9

Your < and > are being treated as delimiters, instead of part of the expression. Use:

$pattern = '#<img src="/img/smile/(.*?).gif">#';

See the php.net regexp delimiters documentation (third code example, and top user note)

Sign up to request clarification or add additional context in comments.

7 Comments

Someone care to explain why they think this correct answer is incorrect?
My guess is that someone thinks that slashes have to be escaped, or that the delimiter has to be a slash which is completely wrong.
I just realised that < > pair cannot be delimiters, they are different. His code just does not make any sense. It would not work at all.
Nice catch! Also, +1!
@Segabond actually, you can use paired delimiters, not just repeated characters i.e. [expr] or {expr} not just /expr/
|
6

You need to use a delimiting characters in your pattern and escape this character inside.

$pattern = '/<img src="\/img\/smile\/(.*?).gif">/';

Or

$pattern = '@<img src="/img/smile/(.*?).gif">@';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.