Saturday, November 30, 2013

How to use str_replace function

Define:
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

Syntax:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Parameters:
If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

$search parameter: The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.
subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
count

If passed, this will be set to the number of replacements performed.

Return Values
This function returns a string or an array with the replaced values.

# Example 1: 
<?php// Provides: Welcome to PHP.net. You are learning "How to use str_replace function" lession.$string  "Welcome to PHP.net. You are learning "How to use str_replace function" lession.";

$search 
= array("PHP.net", "Welcome to");
 
$replace = array("PHP tutorial example""Hello");
$new_string str_replace($search$replace$string);
echo 
$new_string; //output: 
//Hello PHP tutorial example. You are learning "How to use str_replace function" lession.
?>
#Example 2
To collapse multiple consecutive space characters to a single one, don't use str_replace() inside a loop--use preg_replace() instead for clarity and better performance:

<?php

$str
= ' This is    a    test   ';
$str = preg_replace('/ +/', ' ', $str);

?>
 
 
#Example 3: Examples of potential str_replace() gotchas
<?php// Order of replacement$str     "Line 1\nLine 2\rLine 3\r\nLine 4\n";$order   = array("\r\n""\n""\r");$replace '<br />';
// Processes \r\n's first so they aren't converted twice.$newstr str_replace($order$replace$str);
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A''B''C''D''E');$replace = array('B''C''D''E''F');$subject 'A';
echo 
str_replace($search$replace$subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a''p');$fruit   = array('apple''pear');$text    'a p';$output  str_replace($letters$fruit$text);
echo 
$output;?>
 

No comments:

Post a Comment