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

I have below string:

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

And I want to add plus (+) character before every un-double quotes words and double quotes like below:

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

Is there any way to perform such action? I tried with str_replace and regex but cant figure out how to do it.



Solution 1:[1]

You can use this alternation based 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 Demo

"[^"]*"|\S+ is the regex that matches a double quoted text OR any non-space word and replacement is +$0 that prefixes each match with +.

Solution 2:[2]

Use this pattern:

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

Online Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2