PHP/String/String Replace

Материал из Web эксперт
Версия от 07:07, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Quantifier Syntaxes

Quantifier   Min        Max               Range
{m}          m          m                 Exactly m times
{m, x}       m          x                 At least m times, no more than x
{m,}         m          Infinite          At least m times or more
*            0          Infinite          Zero or more times
?            0          1                 Zero or one times
+            1          Infinite          One or more times



Replace the tag content without getting rid of any attributes

<?php
     $string = "<a href=\"http://www.wbex.ru/\">wbex.ru</a><br />" ;
   
     $pattern = "/<a(.*?)>.*?<\/a>/i";
     $replacement = "<a\1>Click!</a>";
   
     $string = preg_replace($pattern, $replacement, $string);
     print($string);
?>



Replacing a Pattern with a Found String

<html>
<head>
<title>preg_replace</title>
</head>
<body>
<?php
     $string = "<a href=\"http://www.wbex.ru/\">wbex</a><br />";
   
     $pattern = "/<a[ .]*?(href *= *".*?").*?>(.*?)<\/a>/i";
     $replacement = "\2: <a \1>\1</a>";
   
     $string = preg_replace($pattern, $replacement, $string);
     print($string);
?>
</body>
</html>



String replace: index and value

<?
print(substr_replace("ABCDEFG", "-", 2, 3));
?>



String replace with Regular Expressions

<?
$old_string = "I really love programming in ASP!";
$new_string = ereg_replace("ASP", "PHP", $old_string);
echo "$new_string";
?>



str_replace: @ (at)

<?php
   $author = "j@wbex.ru";
   $author = str_replace("@","(at)",$author);
   echo "Contact the author of this article at $author.";
?>



What happens when multiple instances of the search string overlap?

<?
$tricky_string = "ABA is part of ABABA";
$maybe_tricked = str_replace("ABA", "DEF", $tricky_string);
print("Substitution result is "$maybe_tricked"<BR>");
?>