callbackpreg-replacephp-5.6ereg

PHP upgrade from 4 to 5 requires changing ereg_replace() and ereg() with delimiters


When running former PHP 4 pages in PHP5 I get Deprectiated errors: I know there are some back slashes that go in there. (or is it forward slashes?) but the " +" item to replace throws me off.

Function ereg_replace() is deprecated:

$perms = ereg_replace(" +", "&", @trim($tmp[0]));

Now this one below really has my mind bent. Only after wearing out my keyboard G-O-O-G-L-E keys did I take a chance and just paste in some code. I decided to answer this question with the hopes of helping someone as challenged as me. What the heck is a "callback function"? I know, I probably use this stuff all day long in other programming languages. Oh well. I think my anxiety level overclowded my correct selection of a forum to answer my simple beginner questions.

preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead:

$string = preg_replace("/&#([0-9]+)/e","chr('\\1')",$string);

My confusion in other StackOverKnow threads and answers is examples are too elaborate. I think someone (including me) could benefit from someone simply typing in the example fixed in correct sytax. I just don't live around this subject that much and because of the millions of lines of code in this RTF generator I'm having to upgrade I'm scared of the "sprong!" effect: I change something and cascading problems occur and I can never change it back.

We purchased a nifty RTF Generator for our club to generate a Word document from our PHP list of hikes. This is where I am finding the Depreciated errors. Just sayin', someday you might need a Word document created from PHP. Hard to find this stuff and it has worked well for the last 9 years.


Solution

  • The " +" is confusing because double quotes and plus sign made me think it was part of the function, not the input.

    $perms = ereg_replace(" +", "&", @trim($tmp[0]));
    
    answer: preg_replace("/ +/", "&", @trim($tmp[0]));
    

    This one had me scratching my head about "what function? there is no function!" until I found this almost obscure example and picked the middle solution:

    preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead:

    $string = preg_replace("/&#([0-9]+)/e","chr('\\1')",$string);
    
    $string = preg_replace_callback("/&#([0-9]+)/", create_function ('$matches', 'return chr($matches[1]);'),$string);
    

    I found This link with comparsions between Depreciated and Replacement to be very useful.