我希望使用PHP的preg_replace()搜索文本中某个单词的出现情况,并将该单词括在括号中,除非已经有括号。这里的挑战是,我想测试方括号,这些括号可能与我正在寻找的文本直接相邻,也可能不相邻。
随机示例:我想用warfarin替换[[warfarin]]
此字符串中的Use warfarin for the prevention of strokes
Use [[warfarin]] for the prevention of strokes (括号已经存在)G 217我可以满足前两个要求,可以使用查找和展望断言:
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在最后一个示例中,应该在单词而不是中添加方括号,因为它包含在一个更长的表达式中,该表达式已经包含在方括号中。
问题是PHP的regexp断言必须有固定的长度,否则就会非常简单。
我在用
PHP 5.3.10-1ubuntu3.1 with Suhosin-Patch (cli) (built: May 4 2012 02:20:36)提前感谢!
发布于 2012-05-20 09:54:55
这就是我会做的。
$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;会导致
原件:
使用华法林预防中风。使用[华法林]预防中风。使用[通用华法林制剂]预防中风
更改:
使用[华法林]预防中风。使用[华法林]预防中风。使用[通用华法林制剂]预防中风
发布于 2012-05-20 09:54:10
试试这个:
echo preg_replace( "/(warfarin)([^\]]+(\[|$))/", "[[$1]]$2", "Use generic warfarin[[ formulation for]] the prevention of strokes\n" );我假设没有方括号就不会有结束括号的情况。
https://stackoverflow.com/questions/10672286
复制相似问题