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 和正则表达式,但不知道该怎么做。

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

$re = '/"[^"]*"|\S+/m'; 
$str = 'this is a "text field" need "to replace"'; 

$result = preg_replace($re, '+[=10=]', $str);
//=> +this +is +a +"text field" +need +"to replace"

RegEx Demo

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

使用这个模式:

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

Online Demo