Monday, 28 September 2020

SOLVED - How can I convert ereg expressions to preg in PHP?

 

How can I convert ereg expressions to preg in PHP?


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

PROBLEM -

eregi('^hello world');

 

Addition of delimiters is the biggest change in syntax -

ereg('^hello', $str); preg_match('/^hello/', $str);
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.

 The most used is the case-insensitive modifier i, the alternative to eregi:

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

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

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

0 comments:

Post a Comment

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel