0

I have a code like

 $newstr = preg_replace_callback("/<p>(.+?)</p>/", function($matches) 
 {
    return str_replace($matches[1], '<b>' . $matches[1] . '</b>', $matches[0]);
 }, $str);

It replaces if a single line string is given like this

 '<p>Hello World and Hello Universe</p>'

but fails when multiple lines are given like

  '<p>Hello World and
         Hello Universe</p>'

How it can be handled? If for test purpose I give string like this

  '<p>Hello World and'.
         'Hello Universe</p>'

It works but the problem is this string is coming from a textarea and cannot understand what to do?

3
  • use the s modifier to allow multiline statements Commented Feb 16, 2014 at 12:03
  • Thanks @Tularis Amal suggested that. Commented Feb 16, 2014 at 12:06
  • I know, posted this at the same time as amal did Commented Feb 16, 2014 at 12:08

1 Answer 1

0

Use the s modifier (also called DOTALL modifier). The dot metacharacter, by default, matches everything except newlines. The s modifier makes it match newlines as well:

$newstr = preg_replace_callback("~<p>(.+?)</p>~s", function($matches) {
    return str_replace($matches[1], '<b>' . $matches[1] . '</b>', $matches[0]);
}, $str);

Demo

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

3 Comments

Thanks Amal it worked. I am really weak at Regex it was suggested by Mika a great one.
@JohnSmith: Glad I could help. I suggest going through regular-expressions.info - It's a great resource for learning regex :)
Thanks for the link I will see that and will accept answer after 10 minutes as required by SO

Your Answer

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