Hi,

I thought I had set out to do something simple but turns out maybe its not...

I have a string $str that contains [code] blah blah [/code] tags. All I would like to do is replace the content of the code tag with htmlspecialchars('[code] blah blah [/code]')

I figured preg_replace would be my best option so I finally figured out an expression that would work. The expressions I found online didn't seem to work for my newlines... Anyways so I found this expression to work:

'/[code][\s\S]*[\/code]/i'

So I thought every thing was good and I tried to do this:
$str = preg_replace('/[code][\s\S]*[\/code]/i', htmlspecialchars('$1'), $str);

No luck! Seems like $1 is empty. If I try putting a regular string ie htmlspecialchars('&') it does work.

Not sure what I am doing wrong but would really appreciate some assistance!

Thanks,

slevytam

    Hi.
    You are in the right direction but there is still some small issues. First of you use both \s and \S. That means you select both whitespace and non-whitespace chars, in other words everything. If you are looking for everything use . instead.

    The reason $1 is empty is becouse you haven't created any subpatterns. You need to use ( and ) to create a subpattern. The first subpattern is $1 second $2 and so on.

    To get the code to not stop with newlines you can add a s to the end of the pattern together with your i. You can also add U to make it ungreedy, atleast I had to do it to work when having more then one code block.

    Then you will get a pattern (including modifiers).
    Pattern: /[code](.+)[\/code]/isU

    Feel free to try at my regex tool. Just remove the end and start tags and select the modfiers from the list to the right :-)

    Hope it helps!

      You'll need to use the "e" modifier in order to execute PHP functions within the replacement expression, something like:

      $newString = preg_replace('/\[code\](.*)\[\/code\]/isUe', "'[code]'.htmlspecialchars('$1').'

      '", $oldString);
      [/code]

        NogDog wrote:

        You'll need to use the "e" modifier in order to execute PHP functions within the replacement expression, something like:

        $newString = preg_replace('/\[code\](.*)\[\/code\]/isUe', "'[code]'.htmlspecialchars('$1').'

        '", $oldString);
        [/code]

        Totally forgot that he was going to use htmlspecialchars and needed the e. Good catch NogDog.

          hey thanks guys,

          i'm at work but as soon as I get home I'll give it a try

          it looks hopeful 🙂

            Yes, that worked perfectly. I even added a pre tag into the replace to format things nicely.

            Thanks!

              Write a Reply...