Tag Archives: phpbestpractices

PHP Best Practices #1: Regular expressions

preg not ereg

This is the first in what I hope will be a regular series of posts on PHP best practices, inspired in part by Damian Conway’s Perl Best Practices book.

Historically, PHP has had two incompatible regular expression engines available, POSIX Extended and PCRE (Perl Compatible Regular Expressions). Arguably, Perl-compatible regular expressions are more powerful since they support non-greedy matching, assertions, conditional subpatterns and a number of other features not supported by POSIX Extended. More importantly, the POSIX Extended extension is deprecated as of PHP 5.3, meaning that a call to any of its functions, such as `ereg`, will emit a `E_DEPRECATED` notice. Therefore, for any regular expression functionality in your scripts, use the PCRE set of functions which are prefixed with `preg_`.

Example

    $pattern = '/Hello/x';
    $subject = 'Wake up and say Hello.';
    $matches = array();
    
    if ( preg_match( $pattern, $subject, $matches ) ) {
        print_r( $matches );
    }

Output:

    Array ( [0] => Hello )

Further information

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn