using php preg_replace to replace a whole character string and not replace if string is part of a longer string

假装没事ソ 提交于 2020-06-27 01:38:17

问题


Regular Expressions are completely new to me and having done much searching my expression for testing purposes is this:

preg_replace('/\b0.00%\b/','- ', '0.00%')

It yields 0.00% when what I want is - .

With preg_replace('/\b0.00%\b/','- ', '50.00%') yields 50.00% which is what I want - so this is fine.

But clearly the expression is not working as it is not, in the first example replacing 0.00% with -.

I can think of workarounds with if(){} for testing length/content of string but presume the replace will be most efficient


回答1:


The word boundary after % requires a word char (letter, digit or _) to appear right after it, so there is no replacement taking place here.

You need to replace the word boundaries with unambiguous boundaries defined with the help of (?<!\w) and (?!\w) lookarounds that will fail the match if the keywords are preceded or followed with word characters:

$value='0.00%';
$str = 'Price: 0.00%';
echo preg_replace('/(?<!\w)' . preg_quote($value, '/') . '(?!\w)/i', '- ', $str);

See the PHP demo

Output: Price: -




回答2:


preg_replace has three arguments as you probably already know. The regular expression pattern to match, the replacement value, and the string to search (in that order).

It appears that your preg_replace regex pattern has word boundries \b it is looking for on either end of the value you are looking for 0.00% which should not really be needed. This looks a bit like a bug to me especially when I plug it into the regex website I use. It works fine there. There is probably a somewhat odd querk with it so you might want to try it without the \b and try something like the start of string ^ and end of string characters $.



来源:https://stackoverflow.com/questions/60011845/using-php-preg-replace-to-replace-a-whole-character-string-and-not-replace-if-st

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