Skip to content
Advertisement

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.

Advertisement

Answer

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 +.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement