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

PHP Home Page

Manual Table of Contents
Up to PCRE
Quick Reference
German version of this pageJapanese version of this pageItalian version of this pageFrench version of this pageHungarian version of this page
PCRE
* preg_match
* preg_match_all
* preg_replace
* preg_split
* preg_quote
* preg_grep
* Pattern Modifiers
* Pattern Syntax
Manual: preg_replace
View the source code for this pageSearch the site



Previous page
 preg_match_all
 Updated
Sat, 12 Aug 2000
preg_split 
Next page


preg_replace

(PHP3 >= 3.0.9, PHP4 )

preg_replace -- Perform a regular expression search and replace

Description

mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])

Searches subject for matches to pattern and replaces them with replacement . If limit is specified, then only limit matches will be replaced; if limit is omitted or is -1, then all matches are replaced.

Replacement may contain references of the form \\n. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

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

Every parameter to preg_replace() can be an array.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string; then this replacement string is used for every value of pattern. The converse would not make sense, though.

/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Example 1. Replacing several values


$patterns = array ("/(19|20\d{2})-(\d{1,2})-(\d{1,2})/", 
                   "/^\s*{(\w+)}\s*=/");
$replace = array ("\\3/\\4/\\1", "$\\1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");
      
This example will produce:

$startDate = 5/27/1999
     

Example 2. Using /e modifier


preg_replace ("/(<\/?)(\w+)([^>]*>)/e", 
              "'\\1'.strtoupper('\\2').'\\3'", 
              $html_body);
      

This would capitalize all HTML tags in the input text.

Example 3. Convert HTML to text


// $document should contain an HTML document.
// This will remove HTML tags, javascript sections
// and white space. It will also convert some
// common HTML entities to their text equivalent.

$search = array ("'<script[^>]*?>.*?</script>'si",  // Strip out javascript
                 "'<[\/\!]*?[^<>]*?>'si",  // Strip out html tags
                 "'([\r\n])[\s]+'",  // Strip out white space
                 "'&(quote|#34);'i",  // Replace html entities
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(\d+);'e");  // evaluate as php

$replace = array ("",
                  "",
                  "\\1",
                  "\"",
                  "&",
                  "<",
                  ">",
                  " ",
                  chr(161),
                  chr(162),
                  chr(163),
                  chr(169),
                  "chr(\\1)");

$text = preg_replace ($search, $replace, $document);
      

See also preg_match(), preg_match_all(), and preg_split().


User Contributed Notes: preg_replace


jcj@null.net
24-Sep-1999 08:31

Note that the original string is <strong>not</strong> modified by this function. The results need to be put in a variable or printed. For example:


<pre>$newstring = preg_replace("/oldtext/i", "newtext", $originalstring);</pre>

Nothing happens to $originalstring, unlike in Perl substitutions.




bill@longboys.net
01-Mar-2000 12:58
On redhat 6.1 the following happened


$mystr="454 443 3343";

$str = preg_replace("/[^0-9]/", "//", $mystr);



One would expect to get all non-numeric values stripped and be left with just the numeric values. This is not the case however, what you get is

$str = "454//443//3343".

To strip the non-numeric, you leave the replacement string without the /'s...ie

$str=preg_replace("/[^0-9]/", "", $mystr);



rodt@webhosting.com
22-Mar-2000 12:02
Am I crazy?

$string = "<table><tr><td>
<!-- BEGIN relatedlinks -->


<!-- END relatedlinks -->
</td></tr><tr><td>";
$reg = "/<!-- BEGIN ". $handle ." -->(.*)<!-- END ". $handle ." -->/sm";

preg_replace($reg, '{'. $name .'}', $string);

The above works, the below doesn't. Any ideas?

preg_replace($reg, "{$name}", $string); // Leaves off the { and }.



evelpides@hotmail.com
07-May-2000 01:10
I want to do the same thing with php3, How can i do this...

Thanks



dragonzap1@aol.com
29-Jun-2000 10:07
{ and } in double-quotes (") are used for defining the order of operations for variable handling, at least, when they're around a variable. (Normally it'd be for stuff like telling the difference between "${$bleh}[5]" and "${$bleh[5]}".) Try using "\{$name}" instead. (but only when "$" immediately follows "{" in the same string)


momerath@proz.com
09-Jul-2000 01:36
the trick: /\{$varname}/ doesnt work for me. that is my whole match string and i have tried it:<pre>
preg_replace("/\{$varname\}/",$replacement,$string);
preg_replace("/{$varname}/" ditto
ditto "/\{\$varname\}/"
ereg_replace("\{$varname}", $replacement, $string);
and the rest of the obvious ones.
</pre>



ma9aba@bath.ac.uk
10-Jul-2000 02:38
Have you tried "\{$myvariable}" ?
It works for me.




vraravam@thoughtworks.com
16-Jul-2000 11:09
I am trying to convert from PERL:


"$branch =~ s/(\.?)(\d+)$/${1}0.$2/;"


How can I do this in PHP 3.0.16?
Thanks in advance



eric@otherways.com
14-Aug-2000 05:50
newbie question, what does it start with / and end with / mean?
like "/(19|20\d{2})-(\d{1,2})-(\d{1,2})/"



 About Notes


Previous page
 preg_match_all
 Updated
Sat, 12 Aug 2000
preg_split 
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.