Replace all symbols php

How to replace special characters in a string with PHP

The str_replace() function is used to replace all occurrences of specific characters with a replacement you specified as its parameters.

Replace dash symbols with underscore symbols

For example, suppose you want to replace the special character dash ( — ) with an underscore ( _ ). Here’s how you do it:

  1. The character to search for
  2. The replacement character
  3. The string to search from

Replace asterisk symbols with and symbols

Here’s another example to replace asterisk symbols ( * ) with and symbols ( & ):

Replace plus and minus with white spaces

You can also replace a special character with a white space.

The example below shows how to remove two special characters + and — with white spaces:

Instead of passing a single value, pass an array as the first argument of the str_replace() function.

The function will then work to replace all occurrences of the values in the array with the second argument.

Finally, you can also pass an array as the second argument:

The str_replace() function will replace any values found following the replacement array order.

In the above example, + will be replaced with / and — gets replaced with > .

When your replacement array count is lower than the search array, then PHP will pass an empty string to replace the remaining search values.

Now you’ve learned how to replace special characters with PHP. Nice!

You can also use the str_replace() function to remove special characters from your string.

I hope this tutorial has been useful for you. 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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

Источник

Читайте также:  Python work with serial
Оцените статью