Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...