0

So i have php function that was written for php 5.6. I think this was the source originally when i put it together. I made a few changes. This is the code i ended up with:

function Format($input){

    //escape input

    $search = array(
            '/\[b\](.*?)\[\/b]/is',
            '/\[i\](.*?)\[\/i]/is',
            '/\[u\](.*?)\[\/u]/is',
            '/\[s\](.*?)\[\/s]/is',
            '/\[img\](.*?)\[\/img\]/is',
            '/\[color=(.*?)\](.*?)\[\/color\]/is',
            '/\[quote=(.*?)\]/e',
            '/\[p\](.*?)\[\/p]/is',
   );
    $replace = array(
            '<b>$1</b>',
            '<i>$1</i>',
            '<u>$1</u>',
            '<s>$1</s>',
            '<img src="$1">',
            '<font style="color:$1;">$2</font>',
            'GenerateQuote($1)',
            '<a style="color:#ff6600" href=https://' . $_SERVER['SERVER_NAME'] .'/(...)/$1>$1</a>'
    );

    return preg_replace($search, $replace, $input);
}

function GenerateQuote($commentID){
    $sqlresult = mysqli_query($db, "(...)");
    (...)
    return $QuoteCode;
}

The function is used to convert BB tags in a piece of text to the corrosponding HTML tags. The quote tag used an /e argument that is not supported anymore in PHP 7.

preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead

Can someone help me migrate this piece of code from PHP 5.6 to PHP 7? I can't figure out how to do it.

Nemesis
  • 3
  • 4
  • I know this has been asked before but i couldn't figure out how to do it in my case from those answers. Sorry. – Nemesis Sep 20 '18 at 06:47

1 Answers1

1

Most of your expression don't contain the e modifier, so they can stay as they are. But you need to split up the arrays, and treat the eval expression separately.

Delete the last two lines from search and replace. Then:

$tmp = preg_replace($search, $replace, $input);

to apply the first six replacements. Then use preg_replace_callback to remove the e modifier:

$tmp = preg_replace_callback('/\[quote=(.*?)\]/', 
  function ($m) { return GenerateQuote($m[1]); },
  $tmp);

The last part is just a simple replacement again (copy paste from your question).

return preg_replace('/\[p\](.*?)\[\/p]/is',
  '<a style="color:#ff6600" href=https://' . $_SERVER['SERVER_NAME'] .'/(...)/$1>$1</a>',
  $tmp);

That should do it, but if you only use GenerateQuote in that one place you could rewrite the function to accept an array and use it directly as a callback.

jh1711
  • 2,288
  • 1
  • 12
  • 20
  • I spent like a few hours on trying to solve this without getting the idea of doing a second preg replace outside of the array. I guess i wasn't thinking straight. Thank you so much :). It all works now. There was no particular order in the array so i just took the quote tag out and handled that one with your preg_replace_callback code after the original preg_replace. Thanks again. – Nemesis Sep 19 '18 at 22:05