用preg_match替换ereg_match [重复]

This question already has an answer here:

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?

</div>

Try this:

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

becomes

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

Note the / around the regex.

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);

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