Php замена пробела в строке

str_replace

Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace .

Чтобы заменить текст на основе шаблона, а не фиксированной строки, используйте функцию preg_replace() .

Список параметров

Если search и replace — массивы, то str_replace() использует каждое значение из соответствующего массива для поиска и замены в subject . Если в массиве replace меньше элементов, чем в search , в качестве строки замены для оставшихся значений будет использована пустая строка. Если search — массив, а replace — строка, то эта строка замены будет использована для каждого элемента массива search . Обратный случай смысла не имеет.

Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.

Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.

Значение замены, будет использовано для замены искомых значений search . Для множества значений можно использовать массив.

Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).

Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject , а результатом функции также будет являться массив.

Если передан, то будет установлен в количество произведённых замен.

Возвращаемые значения

Эта функция возвращает строку или массив с заменёнными значениями.

Примеры

Пример #1 Примеры использования str_replace()

// присваивает: Hll Wrld f PHP
$vowels = array( «a» , «e» , «i» , «o» , «u» , «A» , «E» , «I» , «O» , «U» );
$onlyconsonants = str_replace ( $vowels , «» , «Hello World of PHP» );

// присваивает: 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 );

// присваивает: 2
$str = str_replace ( «ll» , «» , «good golly miss molly!» , $count );
echo $count ;
?>

Пример #2 Примеры потенциальных трюков с str_replace()

// Порядок замены
$str = «Строка 1\nСтрока 2\rСтрока 3\r\nСтрока 4\n» ;
$order = array( «\r\n» , «\n» , «\r» );
$replace = ‘
‘ ;

// Обрабатывает сначала \r\n для избежания их повторной замены.
echo $newstr = str_replace ( $order , $replace , $str );

// Выводит F, т.к. A заменяется на B, затем B на C, и так далее.
// В итоге E будет заменено F, так как замена происходит слева направо.
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘A’ ;
echo str_replace ( $search , $replace , $subject );

Читайте также:  Dynamic Scaling Example

// Выводит: яблорехкорех орех (по вышеуказанной причине)
$letters = array( ‘я’ , ‘о’ );
$fruit = array( ‘яблоко’ , ‘орех’ );
$text = ‘я о’ ;
$output = str_replace ( $letters , $fruit , $text );
echo $output ;
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Замечание о порядке замены

Так как str_replace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Смотрите также примеры на этой странице.

Замечание:

Эта функция чувствительна к регистру. Используйте str_ireplace() для замены без учёта регистра.

Смотрите также

  • str_ireplace() — Регистронезависимый вариант функции str_replace
  • substr_replace() — Заменяет часть строки
  • preg_replace() — Выполняет поиск и замену по регулярному выражению
  • strtr() — Преобразует заданные символы или заменяет подстроки

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.

Читайте также:  Generics in java with examples

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.

Читайте также:  Comic sans шрифт css

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

Источник

Оцените статью