我的正则表达式经验有限,我正在使用 PHP 中的 preg_replace 函数。
我想要替换一个指定的“单词”,该单词不在 [no-glossary]...[/no-glossary] 标签之间。如果单词和标签之间没有空格,或者单词后面有一个空格,那么我的表达式可以工作,但是如果我在单词前放一个空格(预期的情况),它将失败!
下面的例子有效:
$html = '<p>Do not replace [no-glossary]this[/no-glossary] replace this.</p>';
$html = '<p>Do not replace [no-glossary]this [/no-glossary] replace this.</p>';
这不行:
$html = '<p>Do not replace [no-glossary] this [/no-glossary] replace this.</p>';
逐部分解释所使用的模式
/ - find
(?<!\[no-glossary\]) - Not after the [no-glossary] tag
[ ]* - Followed by 0 or more spaces (I think this is the problem)
\b(this)\b - The word "this" between word boundaries
[ ]* - Followed by 0 or more spaces
(?!\[\/no-glossary\]) - Not before the [/no-glossary] tag
/
这里是代码:
$pattern = "/(?<!\[no-glossary\])[ ]*\b(this)\b[ ]*(?!\[\/no-glossary\])/";
$html = '<p>Do not replace [no-glossary] this [/no-glossary] replace this.</p>';
$html = preg_replace($pattern, "that", $html);
print $html;
输出:
<p>Do not change [no-glossary] that [/no-glossary] changethat.</p>
问题:
- 标签之间的单词被更改。
- 第二个单词前面的空格被移除,而它本应该被替换。