POSIX replacements
The methods ereg_replace() and eregi_replace() make replacements in text and feature POSIX regexes.
You can use the ereg_replace() method to make case-sensitive replacements in POSIX regex syntax. The following example demonstrates how to replace an e-mail address in a string with a hyperlink:
Listing 3.
ereg_replace() method
<?php
$origstr = "My e-mail address is: first.last@example.com";
// Syntax is: ereg_replace( regex, replacestr, string )
$newstr = \
ereg_replace("([.[:alpha:][:digit:]]+@[.[:alpha:][:digit:]]+)",
"<a href=\"mailto:\\1\">\\1</a>", $origstr);
print("$newstr\n");
?>
|
This is an incomplete version of a regex to match e-mail addresses, but it shows that ereg_replace() is more powerful than a regular replacement function like str_replace(). When you use a regex, you define rules by which to do searches, instead of searching for literal characters.
With the exception of ignoring case, the eregi_replace() function is identical to ereg_replace():
Listing 4.
eregi_replace() function
<?php
$origstr = "1 BANANA, 2 banana, 3 Banana";
// Syntax is: eregi_replace( regex, replacestr, string )
$newstr = eregi_replace("banana", "pear", $origstr);
print("New string is: '$newstr'\n");
?>
|
This example replaces banana with pear, regardless of case.




