PHP/String/preg replace — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 07:07, 26 мая 2010

$0 is set to the whole match, then $1, $2

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



Converting Line Breaks

 
<?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 "<pre>mac = ", addcslashes($mac, "\n\r"), "\npc = ",
    addcslashes($pc, "\n\r"), "\nunix = ",
    addcslashes($unix, "\n\r"), "</pre>";
?>



e modifier treats the replacement string in preg_replace() as if it were PHP.

 
<?
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<br />\n7/22/04";
$dates = preg_replace( "/([0-9]+)\/([0-9]+)\/([0-9]+)/e","convDate($1,$2,$3)", $dates);
print $dates;
?>



Entity encoding matched text

 
<?php
$html = "The &lt;b&gt; tag makes text bold: <code>&lt;b&gt;bold&lt;/b&gt;</code>";
print preg_replace("@<code>(.*?)</code>@e","html_entity_decode("$1")", $html);
?>



Escape a > character in HTML

 
<?php
  $html = "<p> replace > and >> and >>> </p>";
  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";
?>



Escaping Special Characters

 
<?php
    $html = "<p> replace > and >> and >>> </p>";
    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";
?>



Formatting a Phone Number

 
<?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"; 
} 
?>



Pass a fourth parameter to preg_replace( ) to specify the maximum number of replacements you want to make.

 
<?
    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/e", "strtoupper("$0")", $a, 2);
    print $b;
?>



pass arrays as parameter one and parameter two, and preg_replace() performs multiple replaces

 
<?
    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/e", "strtoupper("$0")", $a);
    print $b;
?>



Pass arrays of regular expressions and replacement strings to preg_replace().

 
<?
$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<br />";
?>



preg_replace

 
<?php
   $text = "This is a link to http://www.wbex.ru/.";
   echo preg_replace("/http:\/\/(.*)\//", "<a href=\"\${0}\">\${0}</a>", $text);
?>



preg_replace with index

 
<?php
    $s = "m@t.ca";
    echo preg_replace ("/^(\w+)@(\w+)\.(\w{2,4})/", "\1 at \2 dot \3", $s);
?>



Quote escaping in backreference replacements

 
<?php
$html = "<code>&lt;b&gt; It"s bold &lt;/b&gt;</code>";
print preg_replace("@<code>(.*?)</code>@e","html_entity_decode("$1")", $html);
print "\n";
$html = "<code>&lt;i&gt; "This" is italic. &lt;/i&gt;</code>";
print preg_replace("@<code>(.*?)</code>@e","html_entity_decode("$1")", $html);
print "\n";
?>



Regular Expression Replacements

 
<?
    $a = "Foo moo boo tool foo";
    $b = preg_replace("/[A-Za-z]oo\b/", "Got word: $0\n", $a);
    print $b;
?>



Remove any doubled-up whitespace

 
<?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 "<pre>{$str}</pre>";
?>



Replace any non-space whitespace, with a space

 
<?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 "<pre>{$str}</pre>";
?>



Replace with regular expression

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



Replacing URLs with Links

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



Replacing using backreferences

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



Replacing with preg_replace()

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



Using Back References with preg_replace()

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



Using preg_replace() to Replace Patterns

 
<?
$test = "this is a test.";
print preg_replace("/a test/", "another test", $test);
?>