★ wanayoo — archive 1999 http://www.php.net/manual/function.ereg-replace.phpNouvelle recherche | Portail wanayoo

PHP Home Page

Manual Table of Contents
Up to Regexps
Quick Reference
German version of this pageJapanese version of this pageItalian version of this pageFrench version of this pageHungarian version of this page
Regexps
* ereg
* ereg_replace
* eregi
* eregi_replace
* split
* spliti
* sql_regcase
Manual: ereg_replace
View the source code for this pageSearch the site



Previous page
 ereg
 Updated
Sat, 12 Aug 2000
eregi 
Next page


ereg_replace

(PHP3 , PHP4 )

ereg_replace -- Replace regular expression

Description

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

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

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

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.

If no matches are found in string, then string will be returned unchanged.

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

Example 1. Ereg_replace() Example


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

See also ereg(), eregi(), and eregi_replace().


User Contributed Notes: ereg_replace


chrislea@luciddesigns.com
13-May-1999 06:04
I, too, really wish that the regular expression stuff was more like Perl. Anyway, one thing that I often do in Perl is get rid of redundant whitespace using something like this:

<pre>
$str =~ s/\s+/ /g;
</pre>

If you want to do this using PHP3, here's a function for ya.

<pre>
$str = eregi_replace("[[:space:]]+", " ", $str);
</pre>



malhavoc@stomped.com
30-Aug-1999 07:45
I've noticed that using a form to submit a string of text to a php script and then just pulling the information out using the form item name (ie, $comments) seems to escape " and ' characters so these \ characters get put into your information.
I've use the
<PRE>ereg_replace("\\\\", " ", $comments);</PRE>
reg ex, albeit simple, to get around this problem. Im not sure if this is a "feature" of how PHP unencodes a string submitted via GET or not, but at least I can get around it.



kalika@sscf.ucsb.edu
31-Aug-1999 12:33
There is also a <b>StripSlashes</b> function in php which works quite well.



04-Sep-1999 11:05
If you want to strip out any extra characters in a string before using it as a number (ie, turn $4, 096.22 into 4096.22) you can use this:
$String = ereg_replace("[^([:digit:][=.=])]", "", $String);

There is probably a better way to do it, but it works.



zot@zotconsulting.com
17-Sep-1999 05:54
The above did not work for me

<PRE>
ereg_replace( "[^0-9.]", "", $moneyprice)
</PRE>
Did the trick. It should be parsed as:
Any char not a number from 0 to 9, or a period.



chrisbolt@home.com
06-Oct-1999 05:55
I may be missing something, but the following code on a Red Hat box:

<PRE>$uptime = `uptime`;
$uptime = eregi_replace("(.*up |, .[0-9] user.*)", "", $uptime);
echo($uptime)</PRE>

returns the uptime of the box, but the same code on a FreeBSD box doesn't parse it correctly. However, the following code does:

<PRE>$uptime = `uptime`;
$uptime = eregi_replace("(.*up |,.[0-9] user.*)", "", $uptime);
echo($uptime)</PRE>

Even though in both, the uptime command shows a space after the comma and before the user count... odd...



redeye@wmis.net
19-Nov-1999 10:50
Just to repeat myself, it seems there is a function called preg_replace, which allows you to use Perl style pattern matching.
ex:
<pre>
$output = preg_replace("/<\/?(html|head|meta|title|body).*>/","",$rawHtml) ## Deletes certain html tags



rkenny@mke.catalystwms.com
24-Nov-1999 03:24
I just got an IIS server up and going with the win32 port of PHP. When I copied over a script that made use of ereg_replace, it broke. I was using it to replace all "'" with "\\'" but the escape character doesn't seem to be necessary on WINNT and in fact it seems to do the ereg_replace automatically. I've got all my ereg_replace lines commented out now and it works just like it did on RHAT.


ip255@yahoo.com
10-Dec-1999 09:55
When trying to represent a literal backslash in a regexp, your source code needs to contain *four* contiguous backslashes (which become two actual backslashes once your double-quoted string is parsed). Example: <pre>$footer = ereg_replace("\\\\\"", "\"", $footer);</pre>

This is unexpected, because it's different from the standard set by Perl -- although Perl would probably be the same way if a regexp were being specified in a string instead of in the // construct.



fabio@internet-idee.net
17-Jan-2000 02:01
<pre>

REGEXPS + ASSOCIATIVE ARRAYS

Use this:

$replace=Array(1 => "one", 2 => "two");
$stage1=ereg_replace("([1-3])","\$replace[\\1]",$test);
eval("\$stage2 = \"$stage1\";");

Have fun! ;)

</pre>



dfx@gmx.at
26-Jan-2000 06:26
to convert "*blabla*" to "<b>blabla</b>", use this:

$newstring = ereg_replace("\\*([^*]*)\\*", "<b>\\1</b>", $string);

note the necessary double escaping of the literal asterisk (\\*)



nova@purdue.edu
11-Feb-2000 09:53
in order to search for a newline you have to search for the ascii value which is 10 so...

$text = ereg_replace(10, "
", $text)

this will replace all newlines with the html equivalent.



rink@springer.cx
27-Feb-2000 12:09
Code code below will change every http://(something) reference to a hyperlink! Yay!

<pre>$it = ereg_replace("http://(([A-Za-z0-9.\-])*)([a-zA-Z0-9])", "<a href=/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2F%5C%26quot%3B%5C%5C0&y=1999
\">\\0</a>",$it);</pre>

Enjoy!



jammy@mindless.com
17-Mar-2000 08:11
To use \W use the preg function. It allows you to use perl regular expressions rather than php ones.



17-Mar-2000 08:34
I wrote some code which uses ereg_replace to replace 'Welcome "to the" world' with 'Welcome to_the world'. It works, like it should but, I need to generalise it to work with quotes that contain more than one space, eg 'Welcome "to the world"' goes to 'Welcome to_the_world'. The code I have atm is:
<PRE>$searchtext = eregi_replace("\"([a-z0-9.\-]*) ([a-z0-9.\-]*)\"", "\\1_\\2",$searchtext);</PRE>
Any suggestions?



mikeb@map.com
29-Mar-2000 02:07
After about an hour of tring different things, I figured out how to replace a string with a entry in an array. You need to use preg_replace but make sure that the array varable is \$array[\\1] and not $array[\\1] or $array['\\1']. Can we do better with this aspect of replace guys?


benl@pacificnet.com
31-Mar-2000 02:24
To replace the carriage return character. You have to replace both the CHR(10) and CHR(13).


rr@isb.net
01-Apr-2000 03:45
replace a search string with the same search string but highlighted:

$text = eregi_replace( "($search)","<font color=red>\\1</font>",$text );



kaj@tenvoorde.cx
02-Apr-2000 11:07
to remove the <head>......</head> sections in a uploaded webpage:

eregi_replace("<head>.*</head>","",$string);




03-Apr-2000 02:11
I wrote the following regex to convert text in hyperlinks. I think works slightly better than the one already posted.

$tmp = ereg_replace("http://(([A-Za-z0-9.\-])+)([a-zA-Z0-9])((/(([a-zA-Z0-9])*))*)((.([a-zA-Z0-9])+)*)", "<a href=/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2F%5C%26quot%3B%5C%5C0%5C%26quot%3B%26gt%3B%5C%5C0%26lt%3B%2Fa%26gt%3B%26quot%3B%2C%24tmp%29%3B%3C%2Ftt&y=1999>


superdoc@shinbiro.com
14-Apr-2000 12:58
convert in hyperlink...how about this?

$tmp = ereg_replace("((ftp://)|(http://))(([[:alnum:]]|[[:punct:]])*)", "<a href=/old?u=http%3A%2F%2Fwww.php.net%2Fmanual%2F%5C%26quot%3B%5C%5C0%5C%26quot%3B%26gt%3B%5C%5C0%26lt%3B%2Fa%26gt%3B%26quot%3B%2C%24tmp%29%3B%3C%2Ftt&y=1999>


tsyl1@mit.edu
27-Apr-2000 04:40
To make a string all lower case, use strtolower(), not a regexp


Perrault Jean-Paul &lt;pj22@cornell.edu&gt;
17-May-2000 08:51
Try using the PHP str_replace function. For instance, you can do

$text = str_replace("<%Name%>", $name, $text);
------------
I would to replace such Strings "<%String%>" from a HTML-template with the value of $String. i.e. $Name = "Steve" "Hello <%Name%>..." should be replaced with "Hello Steve". This don't works: $text = ereg_replace("<%([^*]*)%>", "${'\\1'}", $text); Does anybody knows a code, that works?



kingmundi@hotmail
08-Jul-2000 08:34
I miss the way C treats strings as an array of characters. I want to zip through a string and remove every character that is not a number. I tried using ereg_replace( "[0-9]", "", $phone_number); but if $phone_number = "23test24"; the variable ends up being just 23 instead of 2324.
This works:

$phone_number = ereg_replace("[^[:digit:]]","",$phone_number);



vraravam@thoughtworks.com
17-Jul-2000 12:36
If you use single wuotes (') instead of (") then you do not need to use the escape sequences (\) on slashes. This way: ereg_replace ('\','\\', $string)


joseph@yesterdayland.com
20-Jul-2000 10:35
If you have a string $test with this info: "This...is...awesome!" and you use this function to change the dots to spaces, you will get weird results. (NOTE: using str_replace instead of ereg_replace solves this problem.)

<pre>
$test = str_replace("...", " ", $text);
</pre>



dino@pod-1.com
24-Jul-2000 05:35
This works for matching newlines of all shapes and sizes:

(\n|\n\015|\015\n)



shayman@quiver.com
27-Jul-2000 12:00
Dear malhavoc@stomped.com,

You can disable the magic quoting of the incoming post/get/cookies from the php.ini file:
;;;;;;;;;;;;;;;;;
; Data Handling ;
;;;;;;;;;;;;;;;;;
magic_quotes_gpc = Off ; magic quotes for incoming GET/POST/Cookie data



elf@messer.de
28-Jul-2000 12:03

// Remove a leading backslash from a single quote to restore

// the original form field's value. (PHP does unwanted quoting.)

$Field[$Key] = ($Value = ereg_replace('\\\\\'', '\'', &$Value));



//$Param .= '{' . $Key . ' "' . addcslashes($Value, '"') . '"} ';

// A quote must be replaced by a "quote" to get a quote with a leading backslash.

// Each single quote must be quoted in a special way to prevent the shell to execute commands in a parameter string.

$Param .= '{' . $Key . ' "'

. ereg_replace('\'', '\'"\'"\'', ereg_replace('"', '"', &$Value))

. '"} ';





pierre-henri@wanadoo.be
03-Aug-2000 01:16
It seem that the regulars expressions has changed in the php 4.
In fact you has to escapes the { and } char in the pattern.



 About Notes


Previous page
 ereg
 Updated
Sat, 12 Aug 2000
eregi 
Next page





Who's responsible for this?
Top of this page

Site
Hosting:



Located in
United States
Elements of this website are subject to copyright.
Questions about installing or using PHP should be directed to one of the mailing lists.
Only questions about the website should be directed to webmaster@php.net.