PHP/String/preg replace
Содержание
- 1 $0 is set to the whole match, then $1, $2
- 2 Converting Line Breaks
- 3 e modifier treats the replacement string in preg_replace() as if it were PHP.
- 4 Entity encoding matched text
- 5 Escape a > character in HTML
- 6 Escaping Special Characters
- 7 Formatting a Phone Number
- 8 Pass a fourth parameter to preg_replace( ) to specify the maximum number of replacements you want to make.
- 9 pass arrays as parameter one and parameter two, and preg_replace() performs multiple replaces
- 10 Pass arrays of regular expressions and replacement strings to preg_replace().
- 11 preg_replace
- 12 preg_replace with index
- 13 Quote escaping in backreference replacements
- 14 Regular Expression Replacements
- 15 Remove any doubled-up whitespace
- 16 Replace any non-space whitespace, with a space
- 17 Replace with regular expression
- 18 Replacing URLs with Links
- 19 Replacing using backreferences
- 20 Replacing with preg_replace()
- 21 Using Back References with preg_replace()
- 22 Using preg_replace() to Replace Patterns
$0 is set to the whole match, then $1, $2
<source lang="html4strict">
<?
$match = "/the (car|cat) sat on the (drive|mat)/"; $input = "the cat sat on the mat"; print preg_replace($match, "Matched $0, $1, and $2\n", $input);
?>
</source>
Converting Line Breaks
<source lang="html4strict">
<?php function line_break_set($subject, $type) {
switch ($type) { case "mac": $ending = "\r"; break; case "pc": $ending = "\r\n"; break; default: $ending = "\n"; } return preg_replace("/\r\n|\n\r|\n|\r/", $ending, $subject);
} $str = "Multiple\rtypes of\n\rline breaks\r\nhave been placed within this string\n\nSee?"; $mac = line_break_set($str, "mac"); $unix = line_break_set($str, "unix"); $pc = line_break_set($str, "pc");
echo "mac = ", addcslashes($mac, "\n\r"), "\npc = ", addcslashes($pc, "\n\r"), "\nunix = ", addcslashes($unix, "\n\r"), "";
?>
</source>
e modifier treats the replacement string in preg_replace() as if it were PHP.
<source lang="html4strict">
<? function convDate( $month, $day, $year ) {
$year = ($year < 70 )?$year+2000:$year; $time = ( mktime( 0,0,0,$month,$day,$year) ); return date("l d F Y", $time);
}
$dates = "3/18/03
\n7/22/04";
$dates = preg_replace( "/([0-9]+)\/([0-9]+)\/([0-9]+)/e","convDate($1,$2,$3)", $dates);
print $dates;
?>
</source>
Entity encoding matched text
<source lang="html4strict">
<?php
$html = "The <b> tag makes text bold: <b>bold</b>
";
print preg_replace("@(.*?)
@e","html_entity_decode("$1")", $html);
?>
</source>
Escape a > character in HTML
<source lang="html4strict">
<?php
$html = "replace > and >> and >>>
";print "Original text was: "" . $html . ""\n"; $html = strrev( $html ); $newhtml = preg_replace( "/>(?![^><]+?\/?<)/", ";tl&", $html ); $newhtml = strrev( $newhtml ); print "<b>New text is: "" . $newhtml . ""\n";
?>
</source>
Escaping Special Characters
<source lang="html4strict">
<?php
$html = "replace > and >> and >>>
";print "<b>Original text was: "" . $html . ""\n"; $html = strrev( $html ); $newhtml = preg_replace( "/>(?![^><]+?\/?<)/", ";tl&", $html ); $newhtml = strrev( $newhtml ); print "<b>New text is: "" . $newhtml . ""\n";
?>
</source>
Formatting a Phone Number
<source lang="html4strict">
<?php $regex = "/^(\(?\d{3}\)?)?[- .]?(\d{3})[- .]?(\d{4})$/";
$values = array("1235551234","800.555.1234", "123-555-1234" ); foreach ($values as $value) {
$formattedValue = preg_replace($regex, "(\\1) \\2-\\3", $value); echo $formattedValue . "\n";
} ?>
</source>
Pass a fourth parameter to preg_replace( ) to specify the maximum number of replacements you want to make.
<source lang="html4strict">
<?
$a = "Foo moo boo tool foo"; $b = preg_replace("/[A-Za-z]oo\b/e", "strtoupper("$0")", $a, 2); print $b;
?>
</source>
pass arrays as parameter one and parameter two, and preg_replace() performs multiple replaces
<source lang="html4strict">
<?
$a = "Foo moo boo tool foo"; $b = preg_replace("/[A-Za-z]oo\b/e", "strtoupper("$0")", $a); print $b;
?>
</source>
Pass arrays of regular expressions and replacement strings to preg_replace().
<source lang="html4strict">
<?
$text = "25/12/2009, 14/5/0210. Copyright 2003";
$regs = array( "|\b(\d+)/(\d+)/(\d+)\b|", "/([Cc]opyright) 2003/" );
$reps = array( "$2/$1/$3", "$1 2004" );
$text = preg_replace( $regs, $reps, $text );
print "$text
";
?>
</source>
preg_replace
<source lang="html4strict">
<?php
$text = "This is a link to http://www.wbex.ru/."; echo preg_replace("/http:\/\/(.*)\//", "<a href=\"\${0}\">\${0}</a>", $text);
?>
</source>
preg_replace with index
<source lang="html4strict">
<?php
$s = "m@t.ca"; echo preg_replace ("/^(\w+)@(\w+)\.(\w{2,4})/", "\1 at \2 dot \3", $s);
?>
</source>
Quote escaping in backreference replacements
<source lang="html4strict">
<?php
$html = "<b> It"s bold </b>
";
print preg_replace("@(.*?)
@e","html_entity_decode("$1")", $html);
print "\n";
$html = "<i> "This" is italic. </i>
";
print preg_replace("@(.*?)
@e","html_entity_decode("$1")", $html);
print "\n";
?>
</source>
Regular Expression Replacements
<source lang="html4strict">
<?
$a = "Foo moo boo tool foo"; $b = preg_replace("/[A-Za-z]oo\b/", "Got word: $0\n", $a); print $b;
?>
</source>
Remove any doubled-up whitespace
<source lang="html4strict">
<?php $str = " This line contains\tliberal \r\n use of whitespace.\n\n"; $str = preg_replace("/\s(?=\s)/", "", $str); // Echo out: "This line contains liberal use of whitespace."
echo "{$str}";
?>
</source>
Replace any non-space whitespace, with a space
<source lang="html4strict">
<?php $str = " This line contains\tliberal \r\n use of whitespace.\n\n";
$str = preg_replace("/[\n\r\t]/", " ", $str);
// Echo out: "This line contains liberal use of whitespace."
echo "{$str}";
?>
</source>
Replace with regular expression
<source lang="html4strict">
<?php
$teststring = ""Hello" and "Goodbye.""; $greedyresult = preg_replace("/".*"/", ""***"", $teststring); $nongreedyresult = preg_replace("/".*?"/", ""***"", $teststring); echo "Original: $teststring\n"; echo "Greedy Replace: $greedyresult\n"; echo "Non-Greedy Replace: $nongreedyresult\n";
?>
</source>
Replacing URLs with Links
<source lang="html4strict">
<?php
$hostRegex = "([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]*[a-z]"; $portRegex = "(:\d{1,})?"; $pathRegex = "(\/[^?<>#\"\s]+)?"; $queryRegex = "(\?[^<>#\"\s]+)?"; $urlRegex = "/(?:(?<=^)|(?<=\s))((ht|f)tps?:\/\/" . $hostRegex . $portRegex . $pathRegex . $queryRegex . ")/"; $str = "http://home.example.ru."; $str2 = "http://home.example.ru:8181/index.php"; echo $urlRegex . "\n"; $sample1 = preg_replace($urlRegex, "<a href=\"\\1\">\\1</a>", $str); $sample2 = preg_replace($urlRegex, "<a href=\"\\1\">\\1</a>", $str2); echo $sample1 . "\n"; echo $sample2 . "\n";
?
</source>
Replacing using backreferences
<source lang="html4strict">
$members=<<<TEXT Name E-Mail Address
A i@example.ru D k@example.ru M m@example.org B b@example.net TEXT; print preg_replace("/([^@\s]+)@(([-a-z0-9]+\.)+[a-z]{2,})/",
"\\1 at \\2", $members); </source>
Replacing with preg_replace()
<source lang="html4strict">
$members=<<<TEXT Name E-Mail Address
A i@example.ru D k@example.ru M m@example.org B b@example.net TEXT; print preg_replace("/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/",
"[ address removed ]", $members); </source>
Using Back References with preg_replace()
<source lang="html4strict">
//converts dates in dd/mm/yy format to mm/dd/yy format:
<? $test = "25/12/2000"; print preg_replace("|(\d+)/(\d+)/(\d+)|", "$2/$1/$3", $test); ?>
</source>
Using preg_replace() to Replace Patterns
<source lang="html4strict">
<? $test = "this is a test."; print preg_replace("/a test/", "another test", $test); ?>
</source>