php - Replacing content inside double quotes, including double quotes

php, regex, replace

Solution

In light of comments below, I think this will be a better resource for you: http://www.regular-expressions.info/

In order to find "anything can go here" you should use regular expressions. This is what they were made for. A regular expression for that might look something like the answers in this question:

How can I match a quote-delimited string with a regex?

then you would use the function preg_replace() like this:

$return_value = preg_replace('/"[^"]+"/', 'replacement text', $str)

leaving this here anyway:

just escape the content with a backslash:

$rstr = str_replace("Console", "Console.WriteLine(\"$variable\");", $str)

this is mostly useful if you are using variables inside your strings. If it is just a straight text replacement, use single quotes:

$rstr = str_replace("Console", 'Console.WriteLine("Words");', $str)

the single quotes count everything but single quotes as just a character.

Problem

So I decided to have a stab at making a text highlighting system. At the moment, I'm just using `str_replace` to replace a word (e.g. `$rstr = str_replace("Console", "<c>Console</c>", $str` where `$str` is the input string. Something that stumped me was how to replace content inside of speech marks (") and quotes ('). For example, if the string "Console" turned into `Console.WriteLine("Words");`, how would I replace `"Words"` with `<sr>"Words"</sr>` (`<sr>` is defined in an external stylesheet)? I had a though that I could use regex, but 1. I don't know how to write regex, and 2. I don't know how to use regex with `str_replace`. My workaround solution: ``` function hlStr($original) { $rstr = explode('"', $original); return $rstr[0].'<sr>"'.$rstr[1].'"</sr>'.$rstr[2]; } ```

Original source

Related problems