使用 php preg_replace 替换整个字符串,如果字符串是较长字符串的一部分,则不替换 [英] using php preg_replace to replace a whole character string and not replace if string is part of a longer string

查看:35
本文介绍了使用 php preg_replace 替换整个字符串,如果字符串是较长字符串的一部分,则不替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式对我来说是全新的,为了测试目的,我已经做了大量的表达式搜索:

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%')

当我想要的是 - 时,它会产生 0.00%.

It yields 0.00% when what I want is - .

使用 preg_replace('/\b0.00%\b/','- ', '50.00%') 产生 50.00% 这就是我想要的 -所以这很好.

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

但很明显,表达式不起作用,在第一个示例中,将 0.00% 替换为 -.

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

我可以想到使用 if(){} 的解决方法来测试字符串的长度/内容,但假设替换将是最有效的

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

推荐答案

词边界% 之后的 a> 要求紧跟其后出现一个单词字符(字母、数字或 _),因此此处不进行替换.

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

您需要用在 (?<!\w)(?!\w) 环视的帮助下定义的明确边界替换单词边界,这将如果关键字前面或后面是单词字符,则匹配失败:

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);

查看 PHP 演示

输出:价格:-

这篇关于使用 php preg_replace 替换整个字符串,如果字符串是较长字符串的一部分,则不替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆