Php replace substring with string

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

Источник

PHP substr_replace() Function

The substr_replace() function replaces a part of a string with another string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Note: This function is binary-safe.

Syntax

Parameter Values

  • A positive number — Start replacing at the specified position in the string
  • Negative number — Start replacing at the specified position from the end of the string
  • 0 — Start replacing at the first character in the string
  • A positive number — The length of string to be replaced
  • A negative number — How many characters should be left at end of string after replacing
  • 0 — Insert instead of replace

Technical Details

Return Value: Returns the replaced string. If the string is an array then the array is returned
PHP Version: 4+
Changelog: As of PHP 4.3.3, all parameters now accept arrays

More Examples

Example

Start replacing at the 6th position in the string (replace «world» with «earth»):

Example

Start replacing at the 5th position from the end of the string (replace «world» with «earth»):

Example

Insert «Hello» at the beginning of «world»:

Example

Replace multiple strings at once. Replace «AAA» in each string with «BBB»:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Передать параметры командной строки python
Оцените статью