steve steve - 6 months ago 23
PHP Question

Find start and end quotes within a string

I have a string of text as follows:

The nice man said "How's things today" and I replied "All is good thanks".


I would like to replace the double quotes for fontawesome icons. If I do a string replace on double qoutes it works fine. But as expected this just gives me a generic lefthand quote mark for every double quote within the string.

My current code:

$str = The nice man said "How's things today" and I replied "All is good thanks".

$str = str_replace('"', '<i class="fa fa-quote-left" aria-hidden="true"></i>');


Outputs:

The nice man said <i class="fa fa-quote-left" aria-hidden="true"></i>How's things today<i class="fa fa-quote-left" aria-hidden="true"></i> and I replied <i class="fa fa-quote-left" aria-hidden="true"></i>All is good thanks<i class="fa fa-quote-left" aria-hidden="true"></i>.


Desired Output:

The nice man said <i class="fa fa-quote-left" aria-hidden="true"></i>How's things today<i class="fa fa-quote-right" aria-hidden="true"></i> and I replied <i class="fa fa-quote-left" aria-hidden="true"></i>All is good thanks<i class="fa fa-quote-right" aria-hidden="true"></i>.




Example Output: http://jsfiddle.net/JfGVE/1975/

Answer Source

If you are sure double quotes are there as the same as what we are seeing in the subject string (balanced, no escaped double quote inside) then a regex will do the job:

echo preg_replace('~(")([^"]+)(")~', '<i class="fa fa-quote-left" aria-hidden="true"></i>\\2<i class="fa fa-quote-right" aria-hidden="true"></i>', $str);

Live demo