Функция замены строки php

PHP str_replace

The PHP str_replace() function returns a new string with all occurrences of a substring replaced with another string.

The following shows the syntax of the str_replace() function:

str_replace ( array|string $search , array|string $replace , string|array $subject , int &$count = null ) : string|arrayCode language: PHP (php)

The str_replace() has the following parameters:

  • The $search is a substring to be replaced.
  • The $replace is the replacement string that replaces the $search value.
  • The $subject is the input string
  • The $count returns the number of replacements that the function performed. The $count is optional.

If the $search and $replace arguments are arrays, the str_replace() takes each value from the $search array (from left to right) and replaces it with each value from the $replace array.

If the $replace array has fewer elements than the $search array, the str_replace() function uses an empty string for the replacement values.

If the $search is an array and the $replace is a string, then the str_replace() function replaces every element in the $search with the $replace string.

Note that the str_replace() doesn’t change the input string ( $subject ). It returns a new array with the $search replaced with the $replace .

Читайте также:  Css center from top

PHP str_replace() function examples

Let’s take some examples of using the PHP str_replace() function.

Simple PHP str_replace() function examples

The following example uses the str_replace() function to replace the string ‘Hello’ with ‘Hi’ in the string ‘Hello there’ :

 $str = 'Hello there'; $new_str = str_replace('Hello', 'Hi', $str); echo $new_str . '
'
; // Hi there echo $str . '
'
; // Hello there
Code language: PHP (php)
Hi there Hello thereCode language: PHP (php)

As shown in the output, the str_replace() doesn’t change the input string but returns a new string with the substring ‘Hello’ replaced by the string ‘Hi’ ;

The following example uses the str_replace() function to replace the substring ‘bye’ with the string ‘hey’ in the string ‘bye bye bye’ :

 $str = 'bye bye bye'; $new_str = str_replace('bye', 'hey', $str); echo $new_str; // hey hey heyCode language: PHP (php)
hey hey heyCode language: PHP (php)

PHP str_replace() function with the count argument example

The following example uses the str_replace() function with the count argument:

 $str = 'Hi, hi, hi'; $new_str = str_replace('hi', 'bye', $str, $count); echo $count; // 2Code language: PHP (php)

In this example, the str_replace() function replaces the substring ‘hi’ with the string ‘bye’ in the string ‘Hi, hi, hi’ .

The count returns two because the str_replace() function only replaces the substring ‘hi’ not ‘Hi’ .

PHP str_replace() function with multiple replacements example

The following example uses the str_replace() function to replace the fox with wolf and dog with cat in the string ‘The quick brown fox jumps over the lazy dog’ :

 $str = 'The quick brown fox jumps over the lazy dog'; $animals = ['fox', 'dog']; $new_animals = ['wolf', 'cat']; $new_str = str_replace($animals, $new_animals, $str); echo $new_str;Code language: PHP (php)
The quick brown wolf jumps over the lazy catCode language: PHP (php)

Since the str_replace() function replaces left to right, it might replace previously replaced value while doing multiple replacements. For example:

 $str = 'apple'; $fruits = ['apple', 'orange', 'banana']; $replacements = ['orange', 'banana', 'strawberry']; $new_str = str_replace($fruits, $replacements, $str, $count); echo $new_str; // strawberry echo $count; // 3Code language: PHP (php)

In this example, the string apple is replaced with orange, orange is replaced with banana, and banana is replaced with strawberry. The returned string is strawberry.

PHP str_ireplace() function

To search for a string case-insensitively and replace it with a replacement string, you use the str_ireplace() function. For example:

 $str = 'Hi, hi, hi'; $new_str = str_ireplace('hi', 'bye', $str, $count); echo $new_str; // bye, bye, byeCode language: PHP (php)

In this example, the str_ireplace() function replaces the substring ‘hi’ or ‘Hi’ with the string ‘bye’ .

Summary

  • Use the str_replace() function to replace a substring with another string.
  • Use the str_ireplace() function to search a substring case-insensitively and replace it with another string.

Источник

PHP: str_replace — замена или удаление подстроки в строке

Функция str_replace в php нужна для замены подстроки в строке.

У функции следующие параметры:

$result = str_replace('что меняем', 'на что меняем', 'в чем меняем');

Замена подстроки

Пример: заменим bbb на zzz:

$str = 'aaa bbb ccc bbb ddd'; $result = str_replace('bbb', 'zzz', $str); echo $result; // результат: aaa zzz ccc zzz ddd

Мы заменили «bbb» на «zzz» и в $result запишется строка «aaa zzz ccc zzz ddd». У нас было 2 вхождения подстроки bbb и мы заменили их на zzz.

А что если нам нужно также заменить и ccc на zzz? Мы бы конечно могли запустить функцию 2 раза, в первый раз заменив первую подстроку, а второй раз другую, но можно просто указать массив подстрок поиска первым параметром.

Пример: заменим bbb и ccc на zzz:

$str = 'aaa bbb ccc bbb ddd'; $result = str_replace(['bbb', 'ccc'], 'zzz', $str); echo $result; // результат: aaa zzz zzz zzz ddd

Что если нам нужно заменить bbb на zzz, а ccc на www?

Мы конечно снова можем запустить функцию 2 раза, но оптимальнее с точки зрения производительности будет и вторым параметром передать массив. В первом массиве будут подстроки, которые мы ищем, а во втором те, на которые заменяем.

Пример: заменяем bbb на zzz, а ccc на www:

$str = 'aaa bbb ccc bbb ddd'; $result = str_replace(['bbb', 'ccc'], ['zzz', 'www'], $str); echo $result; // результат: aaa zzz www zzz ddd

Результат у нас правильный, но читабельность конечно страдает. А представьте если бы мы указывали сразу 50 таких строк для замены? И потом когда мы добавляем или заменяем строку, ее приходилось бы искать в 2 местах.

Более читабельным был бы код:

$str = 'aaa bbb ccc bbb ddd'; $replaces = [ 'bbb' => 'zzz', 'ccc' => 'www', ]; $result = str_replace(array_keys($replaces), array_values($replaces), $str); echo $result; // результат: aaa zzz www zzz ddd

Тут нам помогли функции array_keys и array_values которые вернули все ключи и все значения соответственно. Кстати для подобной замены вам не обязательно использовать функцию str_replace, а можно воспользоваться strtr, и тогда наш код выглядел бы еще более просто:

$str = 'aaa bbb ccc bbb ddd'; $result = strtr($str, [ 'bbb' => 'zzz', 'ccc' => 'www', ]); echo $result; // результат: aaa zzz www zzz ddd

У функции str_replace также есть четвертый параметр $count, в котором мы ничего не передаем, а наоборот получаем количество вхождений.

Таким образом если дополнить наш пример:

$str = 'aaa bbb ccc bbb ddd'; $result = str_replace('bbb', 'zzz', $str, $count); echo $result; // результат: aaa zzz ccc zzz ddd echo 'Вхождений: ' . $count; // Вхождений: 2

Удаление подстроки

Хоть это и очевидно, давайте проговорим еще момент с удалением строк. Чтобы удалить подстроку нужно просто заменить ее на пустоту (пустую строку).

Удалим xx из нашей строки:

str_replace('xx', '', 'aa xx bb'); // вторым параметром у нас идет пустая строка.

Другие примеры

Рассмотрим еще несколько примеров:

// Порядок замены $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); // Выводит: яблорехкорех орех (по вышеуказанной причине) $letters = array('я', 'о'); $fruit = array('яблоко', 'орех'); $text = 'я о'; $output = str_replace($letters, $fruit, $text); echo $output;

Эта функция не поддерживает регулярные выражения, но для этого есть другая функция: preg_replace()

Более мощная альтернатива: preg_replace

С помощью функции preg_replace вы можете осуществлять замену по регулярном выражению. Если вам не хватает возможностей str_replace, то обратите внимание на эту функцию.

Продвинутая работа со строками

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

Взгляните как будут выглядеть поиск и замена строк с помощью symfony/string:

// checks if the string starts/ends with the given string u('https://symfony.com')->startsWith('https'); // true u('report-1234.pdf')->endsWith('.pdf'); // true // checks if the string contents are exactly the same as the given contents u('foo')->equalsTo('foo'); // true // checks if the string content match the given regular expression u('avatar-73647.png')->match('/avatar-(\d+)\.png/'); // result = ['avatar-73647.png', '73647'] // checks if the string contains any of the other given strings u('aeiou')->containsAny('a'); // true u('aeiou')->containsAny(['ab', 'efg']); // false u('aeiou')->containsAny(['eio', 'foo', 'z']); // true // finds the position of the first occurrence of the given string // (the second argument is the position where the search starts and negative // values have the same meaning as in PHP functions) u('abcdeabcde')->indexOf('c'); // 2 u('abcdeabcde')->indexOf('c', 2); // 2 u('abcdeabcde')->indexOf('c', -4); // 7 u('abcdeabcde')->indexOf('eab'); // 4 u('abcdeabcde')->indexOf('k'); // null // finds the position of the last occurrence of the given string // (the second argument is the position where the search starts and negative // values have the same meaning as in PHP functions) u('abcdeabcde')->indexOfLast('c'); // 7 u('abcdeabcde')->indexOfLast('c', 2); // 7 u('abcdeabcde')->indexOfLast('c', -4); // 2 u('abcdeabcde')->indexOfLast('eab'); // 4 u('abcdeabcde')->indexOfLast('k'); // null // replaces all occurrences of the given string u('http://symfony.com')->replace('http://', 'https://'); // 'https://symfony.com' // replaces all occurrences of the given regular expression u('(+1) 206-555-0100')->replaceMatches('/[^A-Za-z0-9]++/', ''); // '12065550100' // you can pass a callable as the second argument to perform advanced replacements u('123')->replaceMatches('/\d/', function ($match) < return '['.$match[0].']'; >); // result = '[1][2][3]'

Как видите здесь есть много полезных методов, для написания которых мы с вами могли бы потратить много времени. Посмотрите также другие полезные примеры работы с symfony/string

Источник

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

Источник

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