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


PHP How to add plus (+) character before double quotes and words without double quotes in string

我有以下字符串:

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

RegEx演示

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

使用此模式:

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

在线演示