phppreg-replacepreg-matchpcreereg

How can I convert ereg expressions to preg in PHP?


Since POSIX regular expressions (ereg) are deprecated since PHP 5.3.0, I'd like to know an easy way to convert the old expressions to PCRE (Perl Compatible Regular Expressions) (preg).

Per example, I have this regular expression:

eregi('^hello world');

How can I translate expressions into preg_match compatible expressions?

Note: This post serves as a placeholder for all posts related to conversion from ereg to preg, and as a duplicate options for related questions. Please do not close this question.

Related:


Solution

  • The biggest change in the syntax is the addition of delimiters.

    ereg('^hello', $str);
    preg_match('/^hello/', $str);
    

    Delimiters can be pretty much anything that is not alpha-numeric, a backslash or a whitespace character. The most used are generally ~, / and #.

    You can also use matching brackets:

    preg_match('[^hello]', $str);
    preg_match('(^hello)', $str);
    preg_match('{^hello}', $str);
    // etc
    

    If your delimiter is found in the regular expression, you have to escape it:

    ereg('^/hello', $str);
    preg_match('/^\/hello/', $str);
    

    You can easily escape all delimiters and reserved characters in a string by using preg_quote:

    $expr = preg_quote('/hello', '/');
    preg_match('/^'.$expr.'/', $str);
    

    Also, PCRE supports modifiers for various things. One of the most used is the case-insensitive modifier i, the alternative to eregi:

    eregi('^hello', 'HELLO');
    preg_match('/^hello/i', 'HELLO');
    

    You can find the complete reference to PCRE syntax in PHP in the manual, as well as a list of differences between POSIX regex and PCRE to help converting the expression.

    However, in your simple example you would not use a regular expression:

    stripos($str, 'hello world') === 0