PHP preg_replace non-greedy trouble

后端 未结 2 2028
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 03:57

I\'ve been using the following site to test a PHP regex so I don\'t have to constantly upload: http://www.spaweditor.com/scripts/regex/index.php

I\'m using the follo

相关标签:
2条回答
  • 2021-01-18 04:25

    just an actual example of @Asaph solution. In this example ou don't need non-greediness because you can specify a count. replace just the first occurrence of @ in a line with a marker

     $line=preg_replace('/@/','zzzzxxxzzz',$line,1);
    
    0 讨论(0)
  • 2021-01-18 04:28

    Your non-greedy modifier is working as expected. But preg_match replaces all occurences of the the (non-greedy) match with the replacement text ("" in your case). If you want only the first one replaced, you could pass 1 as the optional 4th argument (limit) to preg_replace function (PHP docs for preg_replace). On the website you linked, this can be accomplished by typing 1 into the text input between the word "Flags" and the word "limit".

    0 讨论(0)
提交回复
热议问题