PHP/String/String Replace

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

Quantifier Syntaxes

   <source lang="html4strict">

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

      </source>
   
  


Replace the tag content without getting rid of any attributes

   <source lang="html4strict">

<?php

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

?>

      </source>
   
  


Replacing a Pattern with a Found String

   <source lang="html4strict">

<html> <head> <title>preg_replace</title> </head> <body> <?php

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

?> </body> </html>

      </source>
   
  


String replace: index and value

   <source lang="html4strict">

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

      </source>
   
  


String replace with Regular Expressions

   <source lang="html4strict">

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

      </source>
   
  


str_replace: @ (at)

   <source lang="html4strict">

<?php

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

?>


      </source>
   
  


What happens when multiple instances of the search string overlap?

   <source lang="html4strict">

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

      </source>