PHP的preg_replace替换文本,除非括号内(PHP preg_replace replac

2019-09-17 09:00发布

我想用PHP的preg_replace()来搜索某个单词出现一个文本,并附,括号内的字,除非已经有括号存在。 这里的挑战是,我想测试支架,可能会或可能不会直接相邻的我期待的文本。

随便举个例子:我想取代warfarin[[warfarin]]

  1. 在此字符串: Use warfarin for the prevention of strokes
  2. 不是在这个字符串: Use [[warfarin]] for the prevention of strokes (括号内已经存在)
  3. 不是在此字符串之一: 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)

提前致谢!

Answer 1:

这是我会怎么做。

$str = 'Use warfarin for the prevention of strokes. ';
$str .= 'Use [[warfarin]] for the prevention of strokes. ';
$str .= 'Use [[generic warfarin formulation]] for the prevention of strokes';
$arr = preg_split('/(\[\[.*?\]\])/',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
// split the string by [[...]] groups
for ($i = 0; $i < count($arr); $i+=2) {
    // even indexes will give plain text parts
    $arr[$i] = preg_replace('/(warfarin)/i','[[$1]]',$arr[$i]);
    // enclose necessary ones by double brackets
}
echo '<h3>Original:</h3>' . $str;
$str = implode('',$arr); // finally join them
echo '<h3>Changed:</h3>' . $str;

将导致

原版的:

使用华法林用于预防中风。 使用[华法林]用于预防中风。 使用[通用华法林配方]用于预防中风

更改:

使用[华法林]用于预防中风。 使用[华法林]用于预防中风。 使用[通用华法林配方]用于预防中风



Answer 2:

尝试这个:

echo preg_replace( "/(warfarin)([^\]]+(\[|$))/", "[[$1]]$2", "Use generic warfarin[[ formulation for]] the prevention of strokes\n" );

我认为不会有右括号无需打开支架的任何情况下。



文章来源: PHP preg_replace replace text unless inside brackets