我有下面的字符串:
'this is a "text field" need "to replace"'
我想在每个非双引号单词和双引号之前添加加号(+),如下所示:
'+this +is +"text field" +need +"to replace"'
有什么办法可以执行这样的动作?我尝试使用str_replace和regex,但无法弄清楚该怎么做。
提前致谢。
您可以使用以下基于交替的正则表达式:
$re = '/"[^"]*"|\S+/m';
$str = 'this is a "text field" need "to replace"';
$result = preg_replace($re, '+$0', $str);
//=> +this +is +a +"text field" +need +"to replace"
"[^"]*"|\S+
是与双引号文本或任何非空格词匹配的正则表达式,替换项是+$0
在每个匹配项的前缀+
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句