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

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

Версия 10:37, 26 мая 2010

case-sensitive?

 
<?
    $string = "this is a test";
    $newstring = str_replace("test", "TEST", $string);
    print $newstring;
?>



mixed str_replace ( mixed needle, mixed replace, mixed haystack [, int &count] )

 
<?
    $string = "this is a test";
    $newstring = str_replace("is", "is not", $string);
    print $newstring;
?>



Replacing Substrings Using str_replace()

 
str_replace() replaces all instances of a string within another string. 

<?php
    $string = "Site contents copyright 2003.";
    $string .= "The 2003 Guide";
    print str_replace("2003","2004",$string);
?>



Replacing Tabs with Spaces

 
<?php
$str = "
\tline
\t\tline
\t\t\tline
\t\t}
\t}
";
$replaced = str_replace("\t", "    ", $str);
echo "<pre>{$replaced}</pre>";
?>



str_replace() accepts arrays for all its arguments

 
<?php
$source = array("a","b" );
$search = array( "a", "2000" );
$replace = array ( "b", "2001" );
$source = str_replace( $search, $replace, $source );
foreach ( $source as $str )
  print "$str<br>";
?>



str_replace demo

 
<?php
    $haystack = "this is a test";
    $newstr = str_replace ("is", "is not", $haystack); 
    echo "$newstr\n";
?>



str_replace() function searches for occurrence in string, replacing all instances with replacement.

 
Its syntax is: string str_replace (string occurrence, string replacement, string string)
<?
$favorite_food = "ice, cream, chicken wings";
$favorite_food = str_replace("chicken wings", "pizza", $favorite_food);
?>



str_replace.php

 
<?php
   $author = "jason@example.ru";
   $author = str_replace("@","(at)",$author);
   echo "Contact $author.";
?>



Switching tabs and spaces

 
<?php
$tabbed = str_replace(" ","\t","this is a test");
$spaced = str_replace("\t"," ","this is a test");
print "With Tabs: <pre>$tabbed</pre>";
print "With Spaces: <pre>$spaced</pre>";
?>



Using str_replace()

 
<?
print str_replace("{class}",$my_class,
                  "<span class="{class}">A<span>
                   <span class="{class}">B</span>");
?>



Using template file

 
<html>
<head><title>{title}</title></head>
<body>
<h1>{headline}</h1>
<h2>By {byline}</h2>
{article}
<hr/>
<h4>Page generated: {date}</h4>
</body>
</html>
////////////////////////
<?php
$page = file_get_contents("article.html");
if ($page === false) {
    die("Can"t read article.html: $php_errormsg");
}
$vars = array("{title}" => "A",
              "{headline}" => "B",
              "{byline}" => "C",
              "{article}" => "<p>D</p>",
              "{date}" => date("l, F j, Y"));
foreach ($vars as $field => $new_value) {
    $page = str_replace($field, $new_value, $page);
}
$result = file_put_contents("dog-article.html", $page);
if (($result === false) || ($result == -1)) {
    die("Couldn"t write dog-article.html: $php_errormsg");
}
?>