ereg_replace

(PHP 3, PHP 4, PHP 5)

ereg_replace -- 替换正则表达式

说明

string ereg_replace ( string pattern, string replacement, string string )

本函数在 string 中扫描与 pattern 匹配的部分,并将其替换为 replacement

返回替换后的字符串。(如果没有可供替换的匹配项则会返回原字符串。)

如果 pattern 包含有括号内的子串,则 replacement 可以包含形如 \\digit 的子串,这些子串将被替换为数字表示的的第几个括号内的子串;\\0 则包含了字符串的整个内容。最多可以用九个子串。括号可以嵌套,此情形下以左圆括号来计算顺序。

如果未在 string 中找到匹配项,则 string 将原样返回。

例如,下面的代码片断输出 "This was a test" 三次:

例子 1. ereg_replace() 例子

<?php

$string
= "This is a test";
echo
str_replace(" is", " was", $string);
echo
ereg_replace("( )is", "\\1was", $string);
echo
ereg_replace("(( )is)", "\\2was", $string);

?>

要注意的一点事如果在 replacement 参数中使用了整数值,则可能得不到所期望的结果。这是因为 ereg_replace() 将把数字作为字符的序列值来解释并应用之。例如:

例子 2. ereg_replace() 例子

<?php
/* 不能产生出期望的结果 */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo
$string;   /* Output: 'This string has   words.' */

/* 本例工作正常 */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo
$string;   /* Output: 'This string has 4 words.' */
?>

例子 3. 将 URL 替换为超连接

<?php
$text
= ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     
"<a href=\"\\0\">\\0</a>", $text);
?>

提示: preg_replace() 函数使用了 Perl 兼容正则表达式语法,通常是比 ereg_replace() 更快的替代方案。

参见 ereg()eregi()eregi_replace()str_replace()preg_match()


add a note add a note User Contributed Notes
Re: ereg_replace
26-Jul-2006 03:18
last comment: please see setlocale() and ctype_alpha().
24-Jul-2006 05:42
Hi! I was asked to make a site that allows users to log in with their names from all over europe

the code is messy and could be shorter but I guess it's easier to understad it this way

<?php

$nick2
=$_POST['nick'];
$nick=stripslashes($nick2);
$nick= ereg_replace("[^A-Za-z0-9 .\-|_AAAAEEIINO
OUUaaaaeeiin
oouuyAaCcCc
EeEeEeGgGgGgGgHh
HhIiIiIiIiIiJjKLlNnOo
OoOoRrSsTt
UuUuUuUuWwYyY
fOoUuAIiOoUuUUuUuUuOO\]"
, "", $nick);
$nick= ereg_replace("<>\/'~^`:", "", $nick);
$nick= ereg_replace(" ", "", $nick);
$nick=trim($nick);

if (
$nick!=$nick2) echo "Nick contains invalid characters<br>";

?>
noname
12-Jul-2006 10:14
Addition:
"<span class=\"highlighted\">\\0</span>" works better ;)
use eregi_replace() for a non-case-sensitive result.
webmaster at nncoders dot nospam dot de
12-Jul-2006 03:43
Watch out when you use it for highlighting text.
It is case sensitive.

<?php
$textvar
= "testTesttest";
$searchstring = "test";

$highlight = ereg_replace($searchstring, "<span class=\"highlight\">".$searchstring."</span>", $textvar);
?>
Highlights like this: [text]Text[text]
The matching word with not matching case isn't parsed.
Joachim Kruyswijk
25-May-2006 03:59
Use mb_ereg_replace() instead of ereg_replace() when working with multi-byte strings!
chrish at shield dot on dot ca
13-Feb-2006 09:43
I was having problems with Microsoft Outlook viewing forms within email.  I was only able to see the first word of the text box after I used the following code.

If I entered words into the text box and used the enter key to give me a CRLF I could see in the returned data the %0D%0A string, so I assumed if I just used the ereg-replace as below it would just replace the %0D%0A with a single space...

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", " ", $string);
  return $new_string;
}

But the form as displayed by Outlook only showed the text upto the first replaced string, then it was blank!
I could view the source of the email and it would show all of the text I expected.

The following will show the correct data in the form

function remove_extra_linebreaks($string) {
   $new_string=ereg_replace("%0D%0A", '+', $string);
  return $new_string;
}
Chris
21-Jan-2006 03:43
I've updated the function a little that was posted below.  I use it to make database field names readable when making a header row.  I needed it to quit putting a space in "GPA" and to put a space in between numbers and letters.

<?php
/**
*  Converts "fieldcontainingGPAInMyDatabaseFrom2005"
*  To      "Field Containing GPA In My Database From 2005"
*/
function innerCapsToReadableText($text) {
  
$text = ereg_replace("([A-Z]) ", "\\1",ucwords(strtolower(ereg_replace("[A-Z]"," \\0",$text))));
   return
ereg_replace("([A-Za-z])([0-9])", "\\1 \\2", $text);
}
?>
codergeek42 at users dot sourceforge.net
22-Dec-2005 01:15
In response to "php dot net at lenix dot de," a cleaner (easier to read) method would be to type-cast the integer as a string by quoting it. For example:

<?php
$foo
= 42;
echo
ereg_replace ( "bar", "$foo" , "foobar" ); /* Would output "foo42". */
?>
benlanc at ster dot me dot uk
23-Aug-2005 06:49
Quite how I managed to get my previous post so wrong, I don't know. Correction follows:
<?php
/* function to turn InterCaps style strings (i.e. CSS Properties in Javascript) to human readable ones */
function deInterCaps($var){
   return
ucfirst(strtolower(ereg_replace("[A-Z]"," \\0",$var)));
}

$interCapsString = "aLoadOfNonsenseToDemonstrateTheFunction";

echo
deInterCaps($interCapsString);

// output: A load of nonsense to demonstrate the function
?>
benlanc at ster dot me dot uk
22-Aug-2005 06:07
<?php
/* function to turn InterCaps style strings (i.e. CSS Properties in Javascript) to human readable ones */
function deInterCaps($var){
   return
ucfirst(strtolower(ereg_replace("[A-Z]"," \\1",$var)));
}

$interCapsString = "aLoadOfNonsenseToDemonstrateTheFunction";

echo
deInterCaps($var);

// output: A load of nonsense to demonstrate the function
?>
php dot net at lenix dot de
07-Jul-2005 06:26
One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that.

If you're ever having trouble with this one there's an easy workarround:

instead of
<?php
$foo
= 23;
echo
ereg_replace ( "bar", $foo , "foobar" );
?>

just do

<?php
$foo
= 23;
echo
ereg_replace ( "bar", "" . $foo , "foobar" );
?>

to replace "bar" inside "foobar" with the string "23".
zaczek at gmail dot com
05-Jul-2005 07:09
If you want the function to process query strings, such as:

http://www.php.net/index.php?id=10%32&wp=test

modify the function as follows:

function hyperlink(&$text)
{
   // match protocol://address/path/
   $text = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $text);

   // match www.something
   $text = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
Sanitization Function
11-Apr-2005 09:09
// Clean potentially nasty stuff from a string
function clean_string($string)
{
   return ereg_replace("[^[:space:]a-zA-Z0-9*_.-]", "", $string);
}
cristiklein at yahoo dot com
10-Apr-2005 05:50
Sometimes, you would like to match both styles of URL links that are common in chat windows:

http://www.yahoo.com
www.yahoo.com

You can do this by using the following code:

<?php
function hyperlink(&$text)
{
  
// match protocol://address/path/
  
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "<a href=\"\\0\">\\0</a>", $text);

  
// match www.something
  
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
}
?>

You can use this function like this:
<?php
$line
= "Check the links: www.yahoo.com http://www.php.net";
hyperlink($line);
// Now, all text that looks like a link becomes a link
?>
bgoodman at osogrande dot com
03-Mar-2005 06:25
When you are dealing with databases you can end up with quite a few \" to deal with.  To ereg_replace all these with something else it requires you to \ the \ and \ the " so you end up with:

$var1 = '\"';
$var2 = ereg_replace('\\\"','1234',$var1);

print $var2;  //this should print 1234
eerie at gmx dot net
28-Feb-2005 03:44
<?php $path = ereg_replace("\\", "/", $path); ?>
as posted from mmtach at yahoo dot com causes an error because you have to escape the backslash twice, once for the quotation marks and a second time due the posix syntax.
<?php $path = ereg_replace("\\\\", "/", $path); ?>
or
<?php $path = ereg_replace('\\', "/", $path); ?>
should both work as expected. since you don't have to escape the backslash in brackets (posix syntax) his alternative works also.
AT-HE ( at_he at h0tmail dot com )
22-Feb-2005 07:08
hi..  i am just learning php since a few days.. i had mount a website in my own pc and want let users to post messages..

anyway, i wrote a very tiny page that let you run some commands remotely, that is useful mostly as example of ereg_replace and shell_exec :D

<!-----run.php-----
<pre>
<?php

$salida
=ereg_replace("<","&lt;",shell_exec($_POST["comando"]));
echo
"comando: ",$_POST["comando"],"<br>",$salida,"<br>";

?>
<form action="run.php" method="post">
comando: <input type="text" name="comando">
</form>

</pre>
-----eof----->

the ereg_replace is only for replace the "<" character at the output for his code, which html reads as a tag..

- first tou must write something in the form..
- when page is opened again it takes it, replaces "<" characters and puts in $salida variable (it may be useful later)..
-  then prints out and you can write something again :)

.. i haven't change the ">" and other characters.. i don't know if you can process the same string changing its lenght in the process..

maybe it becomes illegible after changing patterns of diffrent length such $str=ereg_replace("a","aaaaa",$str), dont know yet.

greetings ;)
mmtach at yahoo dot com
15-Apr-2002 07:04
found problem:
$path = ereg_replace("\\", "/", $path); //dos path to unix
gives warning error: "EREG_EESCAPE"
this does work:
$path = ereg_replace("[\\]", "/", $path);