Php str replace with array

PHP str_replace() Function

Replace the characters «world» in the string «Hello world!» with «Peter»:

Definition and Usage

The str_replace() function replaces some characters with some other characters in a string.

This function works by the following rules:

  • If the string to be searched is an array, it returns an array
  • If the string to be searched is an array, find and replace is performed with every array element
  • If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
  • If find is an array and replace is a string, the replace string will be used for every find value

Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.

Note: This function is binary-safe.

Syntax

Parameter Values

Parameter Description
find Required. Specifies the value to find
replace Required. Specifies the value to replace the value in find
string Required. Specifies the string to be searched
count Optional. A variable that counts the number of replacements

Technical Details

Return Value: Returns a string or an array with the replaced values
PHP Version: 4+
Changelog: The count parameter was added in PHP 5.0

Before PHP 4.3.3, this function experienced trouble when using arrays as both find and replace parameters, which caused empty find indexes to be skipped without advancing the internal pointer on the replace array. Newer versions will not have this problem.

More Examples

Example

Using str_replace() with an array and a count variable:

$arr = array(«blue»,»red»,»green»,»yellow»);
print_r(str_replace(«red»,»pink»,$arr,$i));
echo «Replacements: $i»;
?>

Example

Using str_replace() with fewer elements in replace than find:

$find = array(«Hello»,»world»);
$replace = array(«B»);
$arr = array(«Hello»,»world»,»!»);
print_r(str_replace($find,$replace,$arr));
?>

Источник

str_replace

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

To replace text based on a pattern rather than a fixed string, use preg_replace() .

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.

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

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

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.

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.

Examples

Example #1 Basic str_replace() examples

// Provides: Hll Wrld f PHP
$vowels = array( «a» , «e» , «i» , «o» , «u» , «A» , «E» , «I» , «O» , «U» );
$onlyconsonants = str_replace ( $vowels , «» , «Hello World of PHP» );

// Provides: You should eat pizza, beer, and ice cream every day
$phrase = «You should eat fruits, vegetables, and fiber every day.» ;
$healthy = array( «fruits» , «vegetables» , «fiber» );
$yummy = array( «pizza» , «beer» , «ice cream» );

$newphrase = str_replace ( $healthy , $yummy , $phrase );

// Provides: 2
$str = str_replace ( «ll» , «» , «good golly miss molly!» , $count );
echo $count ;
?>

Example #2 Examples of potential str_replace() gotchas

// Order of replacement
$str = «Line 1\nLine 2\rLine 3\r\nLine 4\n» ;
$order = array( «\r\n» , «\n» , «\r» );
$replace = ‘
‘ ;

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

Notes

Note: This function is binary-safe.

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

Note:

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

See Also

  • str_ireplace() — Case-insensitive version of str_replace
  • substr_replace() — Replace text within a portion of a string
  • preg_replace() — Perform a regular expression search and replace
  • strtr() — Translate characters or replace substrings

User Contributed Notes 34 notes

A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

function str_replace_json ( $search , $replace , $subject ) <
return json_decode ( str_replace ( $search , $replace , json_encode ( $subject )));

>
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

function str_replace_deep ( $search , $replace , $subject )
<
if ( is_array ( $subject ))
<
foreach( $subject as & $oneSubject )
$oneSubject = str_replace_deep ( $search , $replace , $oneSubject );
unset( $oneSubject );
return $subject ;
> else <
return str_replace ( $search , $replace , $subject );
>
>
?>

Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string ‘-aaa—-b-c——d—e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:

$challenge = ‘-aaa—-b-c——d—e—f’ ;
echo str_replace ( ‘—‘ , ‘-‘ , $challenge ). ‘
‘ ;
echo preg_replace ( ‘/—+/’ , ‘-‘ , $challenge ). ‘
‘ ;
?>

This outputs the following:
-aaa—b-c—d-e—f
-aaa-b-c-d-e-f

Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

$arrFrom = array( «1» , «2» , «3» , «B» );
$arrTo = array( «A» , «B» , «C» , «D» );
$word = «ZBB2» ;
echo str_replace ( $arrFrom , $arrTo , $word );
?>

I would expect as result: «ZDDB»
However, this return: «ZDDD»
(Because B = D according to our array)

To make this work, use «strtr» instead:

$arr = array( «1» => «A» , «2» => «B» , «3» => «C» , «B» => «D» );
$word = «ZBB2» ;
echo strtr ( $word , $arr );
?>

This returns: «ZDDB»

Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
$replace = array(
‘dog’ => ‘cat’ ,
‘apple’ => ‘orange’
‘chevy’ => ‘ford’
);

$string = ‘I like to eat an apple with my dog in my chevy’ ;

echo str_replace_assoc ( $replace , $string );

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

function strReplaceAssoc (array $replace , $subject ) <
return str_replace ( array_keys ( $replace ), array_values ( $replace ), $subject );
>
?>

[Jun 1st, 2010 — EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]

As an effort to remove those Word copy and paste smart quotes, I’ve found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an «invisible» character after the †for the right side double smart quote that doesn’t seem to display here. It is chr(157).

$find [] = ‘“’ ; // left side double smart quote
$find [] = ‘”’ ; // right side double smart quote
$find [] = ‘‘’ ; // left side single smart quote
$find [] = ‘’’ ; // right side single smart quote
$find [] = ‘…’ ; // elipsis
$find [] = ‘—’ ; // em dash
$find [] = ‘–’ ; // en dash

$replace [] = ‘»‘ ;
$replace [] = ‘»‘ ;
$replace [] = «‘» ;
$replace [] = «‘» ;
$replace [] = «. » ;
$replace [] = «-» ;
$replace [] = «-» ;

$text = str_replace ( $find , $replace , $text );
?>

As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string. This may produce unexpected output.

$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘ABCDE’ ;

echo str_replace ( $search , $replace , $subject ); // output: ‘FFFFFF’
?>

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet. The expected output for this sample is ‘BCDEF’; however, the actual output is ‘FFFFF’.

To more clearly illustrate this, consider the following example:

$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘A’ ;

echo str_replace ( $search , $replace , $subject ); // output: ‘F’
?>

Since ‘A’ is the only letter in the $search array that appears in $subject, one would expect the result to be ‘B’; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

/**
* When using str_replace(. ), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously. This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements. Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The «o» in «stro_replace» represents «original», indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace ( $search , $replace , $subject )
return strtr ( $subject , array_combine ( $search , $replace ) );
>

$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘ABCDE’ ;

echo stro_replace ( $search , $replace , $subject ); // output: ‘BCDEF’
?>

Some other examples:

// We want to replace the spaces with   and the ampersand with &
echo str_replace ( $search , $replace , $subject ); // output: «Hello&nbsp&&nbspgoodbye!» — wrong!

echo stro_replace ( $search , $replace , $subject ); // output: «Hello & goodbye!» — correct!

/*
Note: Run the above code in the CLI or view source on your web browser — the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>

$search = array( ‘ERICA’ , ‘AMERICA’ );
$replace = array( ‘JON’ , ‘PHP’ );
$subject = ‘MIKE AND ERICA LIKE AMERICA’ ;

// We want to replace the name «ERICA» with «JON» and the word «AMERICA» with «PHP»
echo str_replace ( $search , $replace , $subject ); // output: «MIKE AND JON LIKE AMJON», which is not correct

echo stro_replace ( $search , $replace , $subject ); // output: «MIKE AND JON LIKE PHP», which is correct
?>

Источник

Читайте также:  Изменение цвета текста
Оцените статью