Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

preg_replace('/0.00%/','- ', '0.00%')

It yields 0.00% when what I want is - .

With preg_replace('/0.00%/','- ', '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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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: -


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...