How to Change PHP's Eregi to Preg_Match

How to change PHP's eregi to preg_match

Perl-style regex patterns always need to be delimited. The very first character in the string is considered the delimiter, so something like this:

function validate_email($email) {
if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", $email)) {
echo 'bad email';
} else {
echo 'good email';
}
}

The reason your initial attempt didn't work is because it was trying to use ^ as the delimiter character but (obviously) found no matching ^ for the end of the regex.

How to convert eregi to preg_match?

If you use / as the regex delimiter (ie. preg_match('/.../i', ...)), you need to escape any instances of / in your pattern or php will think it's referring to the end of the pattern.

You can also use a different character such as % as your delimiter:

preg_match('%^http/[0-9]+\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)$%i',$line,$matches)

Eregi to preg_match conversion

eregi('some expression', $input, $matches);

dark magic, chanting, spooky things...

preg_match('/some expression/i', $input, $matches);

You might want preg_match_all() instead, though.

Switching from PHP !ereg and !eregi to preg_match

You have to open and close your regex pattern with a delimiter:

So that:

$regex = "[0-9]{10}";

becomes

$regex = "/[0-9]{10}/";

If you want the pattern to be case insensitive use the i flag

$regex = "/somepattern/i";

How can I convert ereg expressions to preg in PHP?

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


Related Topics



Leave a reply



Submit