0

Dear Sir/m'am How can i replace ther deprecated ereg_replace with preg_replace or str_replace and still have the same functionality as in the code below?

return ereg_replace("^(.*)%%number%%(.*)$","\\1$i\\2",$number);

///this doesnt work

return preg_replace("^(.*)%%number%%(.*)$","\\1$i\\2",$number);

Anyone smarter have a clue?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Koenraad
  • 3
  • 2
  • You don't just replace `ereg_*` with `preg_*` and call it a day. Both functions use different regex syntaxes and you'll have to learn the PCRE syntax. They're not *too* different, though... – BoltClock Jan 21 '11 at 13:14

3 Answers3

1

Try this:

return ereg_replace("^(.*)%%number%%(.*)$","\\1$i\\2",$number);

becomes

return preg_replace("/^(.*)%%number%%(.*)$/","\\1$i\\2",$number);

Note the / around the regex.

jb1785
  • 722
  • 1
  • 7
  • 19
1

I'll go with a read the fabulous manual approach.

The PHP Manual has a section for moving from POSIX Regex to PCRE.

  1. The PCRE functions require that the pattern is enclosed by delimiters.
  2. Unlike POSIX, the PCRE extension does not have dedicated functions for case-insensitive matching. Instead, this is supported using the /i pattern modifier. Other pattern modifiers are also available for changing the matching strategy.
  3. The POSIX functions find the longest of the leftmost match, but PCRE stops on the first valid match. If the string doesn't match at all it makes no difference, but if it matches it may have dramatic effects on both the resulting match and the matching speed. To illustrate this difference, consider the following example from "Mastering Regular Expressions" by Jeffrey Friedl. Using the pattern one(self)?(selfsufficient)? on the string oneselfsufficient with PCRE will result in matching oneself, but using POSIX the result will be the full string oneselfsufficient. Both (sub)strings match the original string, but POSIX requires that the longest be the result.

Good luck,
Alin

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
  • +1 I was facing similar issues like OP but just replacing ereg with preg didn't solve my problems (even with slash delimiters). Your answer points to the right place, difference between two regex flavors, such as PCRE used by preg functions and POSIX ERE used by ereg. Thanks – Wh1T3h4Ck5 Mar 08 '12 at 01:20
0

Perl Compatible Regular Expressions, used by the preg_ functions in PHP require a demarcation character in the pattern string, defining where the actual string pattern starts and ends, and where attributes for extra functionality, such as case insensitivity, is.

For example:

$pattern = "/dog/i"; // Search pattern for "dog", case insensitive.
$replace = "cat";

$subject = "Dogs are cats.";

$result = preg_replace($pattern, $replace, $subject);
mtnielsen
  • 187
  • 8