Welcome to OStack Knowledge Sharing 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...