php regex preg_replace_callback fails to handle mutliple lines

落花浮王杯 提交于 2019-12-11 19:16:42

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/21810777/php-regex-preg-replace-callback-fails-to-handle-mutliple-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!