suche nach in der

preg_split> <preg_replace_callback
Last updated: Fri, 18 May 2012

view this page in

preg_replace

(PHP 4, PHP 5)

preg_replaceSucht und ersetzt mit regulären Ausdrücken

Beschreibung

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Durchsucht die Zeichenkette subject nach Übereinstimmungen mit pattern und ersetzt sie mit replacement.

Parameter-Liste

pattern

Der Ausdruck, nach dem gesucht wird. Es kann entweder eine Zeichenkette oder ein Array mit Zeichenketten sein.

Es stehen auch einige PCRE-Modifikatoren zur Verfügung, inklusive 'e' (PREG_REPLACE_EVAL), der speziell für diese Funktion ist.

replacement

Die Zeichenkette oder das Array mit Zeichenketten zum Ersetzen. Falls dieser Parameter eine Zeichenkette ist und der Parameter pattern ein Array, werden alle Suchmuster durch diese Zeichenkette ersetzt. Falls sowohl pattern als auch replacement Arrays sind, wird jedes Suchmuster pattern durch das Gegenstück aus replacement ersetzt. Wenn das replacement-Array weniger Elemente hat als das pattern-Array, wird jedes überzählige pattern durch die leere Zeichenkette ersetzt.

replacement darf Referenzen in der Form \\n oder (ab PHP 4.0.4) $n enthalten, wobei Letztere vorzuziehen ist. Jede dieser Referenzen wird mit dem Text ersetzt, der vom n-ten eingeklammerten Suchmuster erfasst wurde. n kann einen Wert von 0 bis 99 haben. \\0 oder $0 beziehen sich auf den Text, der auf das komplette Suchmuster passt. Um die Nummer des erfassenden Teil-Suchmusters zu erhalten, werden öffnende Klammern mit 1 beginnend von links nach rechts gezählt. Um einen Backslash im Ersatz zu verwenden, muss er verdoppelt werden ("\\\\" PHP-Zeichenkette).

Wenn Sie mit einer Ersetzung arbeiten wollen, in der auf eine Rückreferenzierung direkt eine weitere Zahl folgt (d.h., direkt nach der Übereinstimmmung mit einem Suchmuster soll eine Zahl kommen), können Sie für Ihre Rückreferenzierung nicht die Schreibweise \\1 verwenden. So würde z.B. \\11 die Funktion preg_replace() verwirren, weil sie nicht weiß, ob Sie die Rückreferenzierung \\1 gefolgt von der Zahl 1 wollen oder nur die Rückreferenzierung \\11. In diesem Fall ist die Lösung, \${1}1 zu verwenden. Damit wird eine isolierte Rückreferenzierung $1 erzeugt und die 1 bleibt ein Buchstabensymbol.

Wenn Sie den Modifikator e verwenden, maskiert diese Funktion ein paar Zeichen (nämlich ', ", \ und NULL) in den Zeichenketten, mit denen die Rückreferenzierungen ersetzen werden. Das wird gemacht, um sicherzustellen, dass keine Syntaxfehler entstehen, wenn Rückreferenzierungen verwendet werden, die einfache oder doppelte Anführungszeichen enthalten (z.B. 'strlen(\'$1\')+strlen("$2")'). Vergewissern Sie sich, dass Sie die Zeichenketten-Syntax von PHP kennen, um genau zu wissen, wie die ausgewertete Zeichenkette aussieht.

subject

Die Zeichenkette oder ein Array mit Zeichenketten zum Durchsuchen.

Falls subject ein Array ist, wird das Suchen und Ersetzen auf jedes Element von subject angewandt und der Rückgabewert ist ebenfalls ein Array.

limit

Die maximal mögliche Anzahl von Ersetzungen für jedes Suchmuster in jeder subject. Standardmäßiger Wert: -1 (kein Limit).

count

Falls angegeben, wird dieser Variable die Anzahl vorgenommener Ersetzungen zugewiesen.

Rückgabewerte

preg_replace() gibt ein Array zurück, falls subject ein Array ist, andernfalls eine Zeichenkette.

Falls Übereinstimmungen gefunden wurden, wird die neue Zeichenkette subject zurückgegeben, andernfalls wird subject unverändert zurückgegeben oder NULL, falls ein Fehler auftrat.

Changelog

Version Beschreibung
5.1.0 Den Parameter count hinzugefügt
4.0.4 Die '$n'-Form für den Parameter replacement hinzugefügt
4.0.2 Den Parameter limit hinzugefügt

Beispiele

Beispiel #1 Die Verwendung von Rückreferenzierungen mit darauf folgenden numerischen Literalen

<?php
$zeichenkette 
'15. April 2003';
$suchmuster '/(\d+)\. (\w+) (\d+)/i';
$ersetzung '${2}1,$3';
echo 
preg_replace($suchmuster$ersetzung$zeichenkette);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

April1,2003

Beispiel #2 Die Verwendung von preg_replace() mit indizierten Arrays

<?php
$zeichenkette 
'Der schnelle braune Fuchs sprang über den faulen Hund.';

$suchmuster = array();
$suchmuster[0] = '/schnelle/';
$suchmuster[1] = '/braune/';
$suchmuster[2] = '/Fuchs/';

$ersetzungen = array();
$ersetzungen[2] = 'Bär';
$ersetzungen[1] = 'schwarze';
$ersetzungen[0] = 'langsame';

echo 
preg_replace($suchmuster$ersetzungen$zeichenkette);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Der Bär schwarze langsame sprang über den faulen Hund.

Wenn wir Suchmuster und Ersetzungen mit ksort() sortieren, sollten wir bekommen was wir wollten.

<?php
ksort
($suchmuster);
ksort($ersetzungen);
echo 
preg_replace($suchmuster$ersetzungen$zeichenkette);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Der langsame schwarze Bär sprang über den faulen Hund.

Beispiel #3 Ersetzen mehrerer Werte

<?php
$suchmuster 
= array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                     
'/^\s*{(\w+)}\s*=/');
$ersetzen = array ('\4.\3.\1\2''$\1 =');
echo 
preg_replace($suchmuster$ersetzen'{startDatum} = 1999-5-27');
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

$startDatum = 27.5.1999

Beispiel #4 Die Verwendung des Modifikators 'e'

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

Das wandelt alle HTML-Tags des durchsuchten Textes in Großbuchstaben um.

Beispiel #5 Leerzeichen entfernen

Dieses Beispiel entfernt überschüssige Leerzeichen aus einer Zeichenkette.

<?php
$str 
'foo   o';
$str preg_replace('/\s\s+/'' '$str);
// Das ist jetzt 'foo o'
echo $str;
?>

Beispiel #6 Die Verwendung des Parameters count

<?php
$anzahl 
0;

echo 
preg_replace(array('/\d/''/\s/'), '*''xp 4 to', -$anzahl);
echo 
$anzahl//3
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

xp***to
3

Anmerkungen

Hinweis:

Bei Verwendung von Arrays für pattern und replacement werden die Schlüssel in der Reihenfolge bearbeitet, in der sie im Array vorliegen. Das ist nicht notwendigerweise dieselbe, wie die numerische Reihenfolge der Indizes. Wenn Sie Indizes verwenden, um festzulegen welches pattern durch welchen Ersatz replacement ersetzt werden soll, sollten Sie vor dem Aufruf von preg_replace() ksort() auf jedes Array anwenden.

Siehe auch



add a note add a note User Contributed Notes
preg_replace
anzenews at volja dot net
13-Jul-2007 02:38
As steven -a-t- acko dot net explained, using /e modifier is tricky if strings have quotes in them. However, the solution might be easier than manual coding of some sort of stripslashes - just use preg_replace_callback instead of preg_replace. It is safer anyway.
anon
13-Jun-2007 02:29
For the benefit of perl coders,

$s =~ s/PATTERN/REPLACEMENT/g;

becomes:

<?
$s
= preg_replace('/PATTERN/', 'REPLACEMENT', $s);
?>

Note that you have to assign the result back to $s.  If your preg_replace doesn't seem to be working, you may have merely forgotten to assign the return to $s.
igasparetto at hotmail dot com
26-Apr-2007 10:21
Displaying results of a search engine:

$words=explode(" ", $_POST['query']);
foreach($words as $word){
    $patterns[]='/'.$word.'/i';
    $replaces[]='<span class="textFound">$0</span>';
}

// run sql

$display_results="";

foreach($res as $row)
    $display_results .= "<p>" . preg_replace($patterns, $replaces, nl2br(htmlentities( $row['field'] ) ) ) . "</p>\n";

echo $display_results;
ismith at nojunk dot motorola dot com
21-Mar-2007 06:47
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.
mrozenoer at overstream dot net
07-Mar-2007 05:30
I could not find a function to unescape javascript unicode escapes anywhere (e.g., "\u003c"=>"<").

<?php
function js_uni_decode($s) {
    return
preg_replace('/\\\u([0-9a-f]{4})/ie', "chr(hexdec('\\1'))"$s);
}
echo
js_uni_decode("\u003c");
?>
dani dot church at gmail dot youshouldknowthisone
07-Feb-2007 08:09
Note that it is in most cases much more efficient to use preg_replace_callback(), with a named function or an anonymous function created with create_function(), instead of the /e modifier.  When preg_replace() is called with the /e modifier, the interpreter must parse the replacement string into PHP code once for every replacement made, while preg_replace_callback() uses a function that only needs to be parsed once.
JON
31-Jan-2007 12:41
for a url explode I would suggest parse_url($url). Its far simpler than the list of preg_replaces used.
Alexey Lebedev
07-Sep-2006 11:21
Wasted several hours because of this:

$str='It&#039;s a string with HTML entities';
preg_replace('~&#(\d+);~e', 'code2utf($1)', $str);

This code must convert numeric html entities to utf8. And it does with a little exception. It treats wrong codes starting with &#0

The reason is that code2utf will be called with leading zero, exactly what the pattern matches - code2utf(039).
And it does matter! PHP treats 039 as octal number.
Try print(011);

Solution:
preg_replace('~&#0*(\d+);~e', 'code2utf($1)', $str);
tim at t-network dot nl
18-Jul-2006 07:58
This function has a little quirk.

When you are trying to use backreferences in the pattern, you MUST use \\n, and not $n. $n doesn't work.
robvdl at gmail dot com
21-Apr-2006 02:15
For those of you that have ever had the problem where clients paste text from msword into a CMS, where word has placed all those fancy quotes throughout the text, breaking the XHTML validator... I have created a nice regular expression, that replaces ALL high UTF-8 characters with HTML entities, such as &#8217;.

Note that most user examples on php.net I have read, only replace selected characters, such as single and double quotes. This replaces all high characters, including greek characters, arabian characters, smilies, whatever.

It took me ages to get it just downto two regular expressions, but it handles all high level characters properly.

$text = preg_replace('/([\xc0-\xdf].)/se', "'&#' . ((ord(substr('$1', 0, 1)) - 192) * 64 + (ord(substr('$1', 1, 1)) - 128)) . ';'", $text);
$text = preg_replace('/([\xe0-\xef]..)/se', "'&#' . ((ord(substr('$1', 0, 1)) - 224) * 4096 + (ord(substr('$1', 1, 1)) - 128) * 64 + (ord(substr('$1', 2, 1)) - 128)) . ';'", $text);
Eric
10-Apr-2006 08:54
Here recently I needed a way to replace links (<a href="blah.com/blah.php">Blah</a>) with their anchor text, in this case Blah. It might seem simple enough for some..or most, but at the benefit of helping others:

<?php

$value
= '<a href="http://www.domain.com/123.html">123</a>';

echo
preg_replace('/<a href="(.*?)">(.*?)<\\/a>/i', '$2', $value);

//Output
// 123

?>
ae at instinctive dot de
28-Mar-2006 05:40
Something innovative for a change ;-) For a news system, I have a special format for links:

"Go to the [Blender3D Homepage|http://www.blender3d.org] for more Details"

To get this into a link, use:

$new = preg_replace('/\[(.*?)\|(.*?)\]/', '<a href="$2" target="_blank">$1</a>', $new);
SG_01
20-Jan-2006 01:43
Re: wcc at techmonkeys dot org

You could put this in 1 replace for faster execution as well:

<?php

/*
 * Removes all blank lines from a string.
 */
function removeEmptyLines($string)
{
   return
preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}

?>
kyle at vivahate dot com
22-Dec-2005 09:08
Here is a regular expression to "slashdotify" html links.  This has worked well for me, but if anyone spots errors, feel free to make corrections.

<?php
$url
= '<a attr="garbage" href="http://us3.php.net/preg_replace">preg_replace - php.net</a>';
$url = preg_replace( '/<.*href="?(.*:\/\/)?([^ \/]*)([^ >"]*)"?[^>]*>(.*)(<\/a>)/', '<a href="$1$2$3">$4</a> [$2]', $url );
?>

Will output:

<a href="http://us3.php.net/preg_replace">preg_replace - php.net</a> [us3.php.net]
istvan dot csiszar at weblab dot hu
21-Dec-2005 10:53
This is an addition to the previously sent removeEvilTags function. If you don't want to remove the style tag entirely, just certain style attributes within that, then you might find this piece of code useful:

<?php

function removeEvilStyles($tagSource)
{
  
// this will leave everything else, but:
   
$evilStyles = array('font', 'font-family', 'font-face', 'font-size', 'font-size-adjust', 'font-stretch', 'font-variant');

   
$find = array();
   
$replace = array();
   
    foreach (
$evilStyles as $v)
    {
       
$find[]    = "/$v:.*?;/";
       
$replace[] = '';
    }
   
    return
preg_replace($find, $replace, $tagSource);
}

function
removeEvilTags($source)
{
   
$allowedTags = '<h1><h2><h3><h4><h5><a><img><label>'.
       
'<p><br><span><sup><sub><ul><li><ol>'.
       
'<table><tr><td><th><tbody><div><hr><em><b><i>';
   
$source = strip_tags(stripslashes($source), $allowedTags);
    return
trim(preg_replace('/<(.*?)>/ie', "'<'.removeEvilStyles('\\1').'>'", $source));
}

?>
jhm at cotren dot net
18-Feb-2005 11:04
It took me a while to figure this one out, but here is a nice way to use preg_replace to convert a hex encoded string back to clear text

<?php
    $text
= "PHP rocks!";
   
$encoded = preg_replace(
          
"'(.)'e"
         
,"dechex(ord('\\1'))"
         
,$text
   
);
    print
"ENCODED: $encoded\n";
?>
ENCODED: 50485020726f636b7321
<?php
   
print "DECODED: ".preg_replace(
      
"'([\S,\d]{2})'e"
     
,"chr(hexdec('\\1'))"
     
,$encoded)."\n";
?>
DECODED: PHP rocks!
gabe at mudbuginfo dot com
18-Oct-2004 10:39
It is useful to note that the 'limit' parameter, when used with 'pattern' and 'replace' which are arrays, applies to each individual pattern in the patterns array, and not the entire array.
<?php

$pattern
= array('/one/', '/two/');
$replace = array('uno', 'dos');
$subject = "test one, one two, one two three";

echo
preg_replace($pattern, $replace, $subject, 1);
?>

If limit were applied to the whole array (which it isn't), it would return:
test uno, one two, one two three

However, in reality this will actually return:
test uno, one dos, one two three
steven -a-t- acko dot net
08-Feb-2004 06:45
People using the /e modifier with preg_replace should be aware of the following weird behaviour. It is not a bug per se, but can cause bugs if you don't know it's there.

The example in the docs for /e suffers from this mistake in fact.

With /e, the replacement string is a PHP expression. So when you use a backreference in the replacement expression, you need to put the backreference inside quotes, or otherwise it would be interpreted as PHP code. Like the example from the manual for preg_replace:

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

To make this easier, the data in a backreference with /e is run through addslashes() before being inserted in your replacement expression. So if you have the string

 He said: "You're here"

It would become:

 He said: \"You\'re here\"

...and be inserted into the expression.
However, if you put this inside a set of single quotes, PHP will not strip away all the slashes correctly! Try this:

 print ' He said: \"You\'re here\" ';
 Output: He said: \"You're here\"

This is because the sequence \" inside single quotes is not recognized as anything special, and it is output literally.

Using double-quotes to surround the string/backreference will not help either, because inside double-quotes, the sequence \' is not recognized and also output literally. And in fact, if you have any dollar signs in your data, they would be interpreted as PHP variables. So double-quotes are not an option.

The 'solution' is to manually fix it in your expression. It is easiest to use a separate processing function, and do the replacing there (i.e. use "my_processing_function('\\1')" or something similar as replacement expression, and do the fixing in that function).

If you surrounded your backreference by single-quotes, the double-quotes are corrupt:
$text = str_replace('\"', '"', $text);

People using preg_replace with /e should at least be aware of this.

I'm not sure how it would be best fixed in preg_replace. Because double-quotes are a really bad idea anyway (due to the variable expansion), I would suggest that preg_replace's auto-escaping is modified to suit the placement of backreferences inside single-quotes (which seemed to be the intention from the start, but was incorrectly applied).

preg_split> <preg_replace_callback
Last updated: Fri, 18 May 2012