我想用PHP的preg_replace()
来搜索某个单词出现一个文本,并附,括号内的字,除非已经有括号存在。 这里的挑战是,我想测试支架,可能会或可能不会直接相邻的我期待的文本。
随便举个例子:我想取代warfarin
与[[warfarin]]
- 在此字符串:
Use warfarin for the prevention of strokes
- 但不是在这个字符串:
Use [[warfarin]] for the prevention of strokes
(括号内已经存在) - 而不是在此字符串之一:
Use [[generic warfarin formulation]] for the prevention of strokes
(“远程”括号已经存在)
我可以用回顾后和向前断言满足前两个条件都正确:
php > echo preg_replace( "/(?<!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use warfarin for the prevention of strokes" );
Use [[warfarin]] for the prevention of strokes
php > echo preg_replace( "/(?<!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use [[warfarin]] for the prevention of strokes" );
Use [[warfarin]] for the prevention of strokes
但我需要与第三个要求你的帮助,当不存在“远程”括号,即不加括号:
php > echo preg_replace( "/(?<!\[\[)(warfarin)(?!]])/", "[[$1]]", "Use [[generic warfarin formulation]] for the prevention of strokes" );
Use [[generic [[warfarin]] formulation]] for the prevention of strokes
在最后一个例子,方括号不应该被加入到word中warfarin
,因为它是包含在已方括号括起来更长的表达。
问题是,PHP的正则表达式断言必须有固定的长度,否则这将是非常简单的。
我正在使用
PHP 5.3.10-1ubuntu3.1 with Suhosin-Patch (cli) (built: May 4 2012 02:20:36)
提前致谢!