ereg_replace

(PHP 4, PHP 5)

ereg_replace — Replace regular expression

Описание

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

This function scans string for matches to pattern , then replaces the matched text with replacement .

Список параметров

pattern

A POSIX extended regular expression.

replacement

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

string

The input string.

Возвращаемые значения

The modified string is returned. If no matches are found in string , then it will be returned unchanged.

Примеры

For example, the following code snippet prints "This was a test" three times:

Пример #1 ereg_replace() example

<?php

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

?>

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. For instance:

Пример #2 ereg_replace() example

<?php
/* This will not work as expected. */
$num 4;
$string "This string has four words.";
$string ereg_replace('four'$num$string);
echo 
$string;   /* Output: 'This string has   words.' */

/* This will work. */
$num '4';
$string "This string has four words.";
$string ereg_replace('four'$num$string);
echo 
$string;   /* Output: 'This string has 4 words.' */
?>

Пример #3 Replace URLs with links

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

Примечания

Подсказка

preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

Коментарии

<?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.
2005-02-27 13:44:45
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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
2005-03-02 16:25:25
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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
?>
2005-04-09 17:50:50
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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);
}
2005-07-05 07:09:53
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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".
2005-07-07 06:26:43
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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
?>
2005-08-22 18:49:14
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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". */
?>
2005-12-21 11:15:53
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
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);
}
?>
2006-01-20 13:43:33
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
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;
}
2006-02-12 19:43:24
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Function to strip an HTML tag out of a string. I use this in part for parsing XML documents.

<?php

function stripTags($tag$string) {
       
// Regular expressions only work with strings if the regexp has been pre-concocted
   
$regExp "<" "$tag" "[^>]*>";

   
$string str_replace("</$tag>"""$string);
   
$string ereg_replace($regExp""$string);
   
    return 
$string;   
}

?>
2007-04-06 12:33:17
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
cristiklein's hyperlink function is nice but works incorrect with a www-string like this

\r\nwww.google.se

then it does not become a hyperlink
2007-05-15 21:03:38
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Your right but you just need to replace by :

<?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);
}
?>
2007-05-30 09:40:04
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
For simple patterns like "[a-z]", preg_replace is up to 6 times faster than ereg_replace.
2007-08-26 05:42:38
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
It's worth mentioning for ultimate clarity that you're safest using double quotes when matching a pattern, since without them, metacharacters will be interpreted as a backslash plus another character. 

Granted, this is part of the language syntax for the string type, but it might not be quite so obvious when dealing with patterns in this function, which is taking the pattern as a parameter.

So if you find that '[\n]' is taking the 'n' out of your string and leaving the new lines alone, switch to doubles before changing anything else.
2007-09-29 21:27:03
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
Code:

<?php

$s 
"Coding PHP is fun.";

$pattern "(.*)PHP(.*)";
$replacement " They say \\1other languages\\2";

print 
ereg_replace($pattern$replacement$s);

?>

Output:
They say Coding other languages is fun.
Explanation:

"PHP" is replaced with "other languages", and the sentence is changed a little, using \1 and \2 to access the parts within parentheses.
http://php-regex.blogspot.com/
2008-01-20 12:02:19
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
If you're not relying on regular expressions, str_replace() can be far faster.
2008-02-29 11:29:29
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
In response to a post above, his coding was a bit wrong.  The correct coding should be :

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

   
// return $text
   
return $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
?>
2008-05-04 10:57:01
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
Just a quick addition to the last post - 

modifying the regular expression for the www clause to include a newline at the begining will allow it to catch URLs that are the first in a line but not the first in a string. The previous version would only catch them if a space preceded the value...

    // match www.something
    $text = ereg_replace("(^| |\n)(www([.]?[a-zA-Z0-9_/-])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
2008-07-03 03:52:47
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
Here is the code I use to make links clickable. The code only works on xxxx:// (i.e. ftp://, http://, etc...). It does not work on www. because that is how I want it. The reason my code has an if condition is that it ignores html links and only modifies non-html urls. (see below)

<?php
function make_clickable($text)
{
   
    if (
ereg("[\"|'][[:alpha:]]+://",$text) == false)
    {
       
$text ereg_replace('([[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/])''<a target=\"_new\" href="\\1">\\1</a>'$text);
    }
    return(
$text); 
}
?>

My function ignores code like this:

<a href="http://php.net"> php.net </a>

But it would make this one click able:

http://php.net
2008-08-06 19:39:36
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
This function makes links unclickable, read the comments:

<?php
function strip_urls($text$repPat)
{
    if(!
$repPat){
       
$repPat "text [url]";
    }
   
$aimpstr 'PHP_STRIP_URLS_FUNCTION_BY_REAL-PHP-GEEK';
   
//change $aimpstr to anything you want.
   
$impstr md5($aimpstr);
   
$text str_replace('</a>''</a>' $impstr$text);
   
$text explode($impstr$text);
   
$n 0;
   
$texta = array();
   
$repPat str_ireplace(array('text''url'), array('\\4''\\2'), $repPat);
    foreach (
$text as $text) {
       
$texta[$n] = ereg_replace("<a(.*)href=\"(.*)\"(.*)>(.*)</a>"$repPat$text);
       
$n++;
    }
   
$textb implode("</a>"$texta);
    return 
$textb;
}

//EXAMPLES:
$string_of_text '<a href="http://www.php.net/">PHP</a> rocks. <a href="http://www.apache.org/">Apache</a> also!';
echo 
strip_urls($string_of_text"text");
echo 
strip_urls($string_of_text"url");
echo 
strip_urls($string_of_text"text [url]");
echo 
strip_urls($string_of_textNULL);
?>
2009-02-01 05:55:20
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
<?php
// highlights the recognized patterns (a good tool for experiments)

$output ereg_replace("your regexp here""<font color=red>\\0</font>"$input)
print 
$output;
?>
2009-03-06 09:17:44
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
Since ereg_replace is now deprecated, many users will be coming to this page, in an attempt to troubleshoot and fix broken scripts after a PHP upgrade.

ereg_replace is essentially a search and replace function and it follows a pattern like this:

<?php

$input 
ereg_replace("find this""replace it with"$output);

?>

You start out by defining the input variable ($input), then the = ereg_replace portion tells php to do a search and replace action on the value of $input, then once the value has been modified with your 'find this' and 'replace with' section, the resulting value is defined as a variable $output which you can then use in other parts of your script or page.

Lets take a real world example.

There is a e-comm site - http://www.example.com - that has millions of item records.  Each item has a name, that is defined as a variable called $title.  Each $title value has spaces, i.e. "Range Cookers" or "Bosch Dishwashers", but we want to convert these into a page url that does not contain spaces, but uses the plus character '+' instead of a space (you can use hyphens '-' or other characters).

If using the deprecated ereg_replace function, it might look something like this:

<?php

$title
=ereg_replace(" ""+"$itemurl);

?>

But to avoid those deprecated errors, we change the function name to preg_replace and add a set of delimiters, in this case the 2 forward slashes / / where the contents inside that are matched as the 'find this' portion.

<?php

$title
=preg_replace("/ /""+"$itemurl);

?>

It is not absolutely necessary to use / / as the delimiters, if you are modifying directory names which may naturally contain forward slashes, it could cause it to break because the slashes in the url or directory would be interpreted as the delimiter, so you could use other obscure characters i.e.  ("# #", "+", $itemurl);  instead.  This would give an output like:

http://www.example.com/-Range+Cooker

http://www.example.com/-Bosch+Dishwasher

This would strip out the spaces from the value of $title and give you a variable called $itemurl where all the spaces were replaced with the plus character, so you could potentially use it as a url like above.

So to summarize:  ereg_replace is a deprecated search and replace action where preg_replace can be used instead, and it follows a pattern as described earlier where it takes the input data, finds a match based on what you are looking for, replaces it with something else you define, and then gives you an output data variable that you can use in your script or page.  Hopefully by understanding the process, the php code functions wont seem like voodoo and you could troubleshoot and fix many of the deprecated errors yourself.
2010-06-25 14:24:30
http://php5.kiev.ua/manual/ru/function.ereg-replace.html
Автор:
Be careful, don't replace all ereg_replace() with str_replace() as many people will likely to recommend if there is regular expression stuffs, or your script will stop running !!!

Example : replace the (.) at the end of the text with (...)

<?php

$text 
"This is a simple text.";

print( 
ereg_replace"\.$""..."$text ) );

?>

Test with str_replace() you will find it's not working.
2010-10-17 22:11:03
http://php5.kiev.ua/manual/ru/function.ereg-replace.html

    Поддержать сайт на родительском проекте КГБ