PHP如何在双引号之前添加加号(+)字符和字符串中没有双引号的单词

时间:2016-04-29 17:50:40

标签: php regex preg-replace preg-match str-replace

我有以下字符串:

'this is a "text field" need "to replace"'

我想在每个非双引号词和双引号之前添加加号(+)字符,如下所示:

'+this +is +"text field" +need +"to replace"'

有没有办法执行此类操作?我尝试使用str_replace和regex,但无法弄清楚如何做到这一点。

先谢谢。

2 个答案:

答案 0 :(得分:4)

您可以使用此基于交替的正则表达式:

$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"

RegEx Demo

"[^"]*"|\S+是匹配双引号文本或任何非空格词的正则表达式,替换为+$0,每个匹配前缀为+

答案 1 :(得分:0)

使用此模式:

/(\b\w+)|("(.*?)")/

Online Demo

相关问题