need an help for ereg_replace (deprecated)

68 views Asked by At

Hello i've writen a few scripts 2 or 3 years ago. Now it's not running. My scripts :

<?php
 function tolink($text){

    $text = " ".$text;
    $text = ereg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target="_blank" rel="nofollow">\\1</a>', $text);
    $text = ereg_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
            '<a href="\\1" target="_blank" rel="nofollow">\\1</a>', $text);
    $text = ereg_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
    '\\1<a href="http://\\2" target="_blank" rel="nofollow">\\2</a>', $text);
    $text = ereg_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4})',
    '<a href="mailto:\\1"  rel="nofollow">\\1</a>', $text);
    return $text;
    }

    ?>

When i replace ereg_replace with preg_replace it gives me an error.

I need your help... Thank you...

1

There are 1 answers

3
Barmar On

All the PCRE functions in PHP require that you surround the regexp with a pair of delimiters, e.g. the / surrounding the regexp in this example:

preg_replace ('/regexp_to_match/', 'replacement', $text);

This allows you to append modifiers to the regexp after the second delimiter, as in:

preg_replace ('#regexp_to_match#i', 'replacement', $text);

which performs a case-insensitive match.

As you can see from those two examples, the delimiters can be any character. The first character of the regexp is taken as the delimiter, and it then looks for its match at the end. If the character is a bracketing character, it looks for its opposite, e.g.

preg_match ('<x*>', $text);

Here's the preg_replace() version of your first substitution.

  $text = preg_replace('<(((f|ht){1}tp://)[-\w@:%+.~#?&/=]+)>',
        '<a href="$1" target="_blank" rel="nofollow">$1</a>', $text);

I've also simplified the regexp: I used \w for word characters instead of listing the alphanumerics explicitly, removed the unnecessary \ before + inside the [...], and changed // to / inside the brackets (the extra slash was redundant). Also, $1 is preferred these days in the replacement, rather than \\1.