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