Php - Replacing content inside double quotes including double quotes

So, I decided to strike a blow at creating a text highlighting system. At the moment I'm just using str_replace

to replace a word (eg $rstr = str_replace("Console", "<c>Console</c>", $str

where $str

is the input string.

Something that made me sick was how to replace the content inside speech marks (") and quotes ("). For example, if the string is " The console "turned into Console.WriteLine("Words");

how would I replace "Words"

with <sr>"Words"</sr>

( <sr>

defined in an external style sheet)?

I had at least that I could use a regex, but 1. I don't know how to write a regex, and 2. I don't know how to use regex with str_replace

.


My decision:
function hlStr($original)
{
    $rstr = explode('"', $original);
    return $rstr[0].'<sr>"'.$rstr[1].'"</sr>'.$rstr[2];
}

      

+3


source to share


2 answers


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

To find "anything can go here" you have to use regular expressions. For this they were created. The regex for this might look something like the answers in this question:

How can I match a quoted delimited string with a regex?

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

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

      




leaving this here anyway:

just remove the backslash content:

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

      

this is mostly useful if you are using variables within your strings. If it's just a direct replacement for text, use single quotes:

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

      

single quotes count everything but single quotes only as a character.

+7


source


This is my decision. Expand the entire line with (") characters, and then run specific code for every second of them. This code does it automatically for every second value after" item ", which means if you do: hej" lol it will change to:, hi <sr>" lol "</sr>

or if you do: hi "with" you; it will change to: hi <sr>" with "</sr> you

etc.



function wrapInside($text,$symbol)
    {
        $string = explode($symbol, $text);
        $i = 1;
        $QS = '';
        foreach( $queryString as $V )
        {
            ( $i == 1 ) ? ( $QS .= $V ) : ( $QS .= '<sr>"'.trim($V).'"</sr>' );
            ( $i == 1 ) ? ( $i = 0 ) : ( $i = 1 );
        }
        $queryString = trim($QS);
        return $queryString;
    }

      

0


source







All Articles