开发者

PHP Preg_replace: can't get the replace part to work, finding is fine

开发者 https://www.devze.com 2023-03-25 03:51 出处:网络
I don\'t know how to do the following: find all instances of \'/\\s[2-9]\\)/\' and replace the space with a <br /> tag.

I don't know how to do the following:

find all instances of '/\s[2-9]\)/' and replace the space with a <br /> tag.

Something as simple as this doesn't work:

$preg_num = ' /\s[2-9]\)/';
$preg_fix = "'/<br>/[2-9]\)'";
preg_replace($preg_num,$preg_fix,$notes);

What do I need to change the $开发者_如何学Pythonpreg_fix variable to?


Using a lookahead is simpler than a backreference, IMHO.

$preg_num = '/\s(?=[2-9]\))/';
$preg_fix = '<br/>';
preg_replace($preg_num,$preg_fix,$notes);

This way, you are only replacing the space with the <br/>.


The replacement string is not treated as a regex — it is more like a literal string. If you are trying to put whatever digit [2-9] that was matched in the original regex into the replacement string, capture the character as a group and use a backreference.

$preg_num = '/\s([2-9])\)/';
$preg_fix = "<br />$1)'";
preg_replace($preg_num,$preg_fix,$notes);

For more information:

  • preg_replace's replacement parameter documentation
  • Regular expression grouping: "Use Round Brackets for Grouping"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号