Php str replace заменить только

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 .

Читайте также:  Cast int to long in java

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.

Источник

How to Replace Only the First Occurrence of a String in PHP?

There are several ways in PHP that you could use to replace only the first match in a string. In this article, we’ve handpicked a few that we believe are good for the job.

For all the examples in this article, we’ll be using the following string to replace the first occurrence of foo:

$str = 'foobar foobaz fooqux';

Can I Use str_replace() to Replace Only the First Match?

By default, PHP’s str_replace() , replaces all occurrences of a match; an optional fourth argument to the function gives the number of replacements performed, and does not help in limiting the number of replacements that will be made. Therefore, it may not be helpful in restricting the number of replacements to only the first find.

Using preg_replace()

The fourth argument to the preg_replace() function can be used to limit the number of times the match is replaced. For example, to limit it to only the first match, you could do the following:

$replaceWith = ''; $findStr = 'foo'; echo preg_replace('/' . $findStr . '/', $replaceWith, $str, 1); // output: "bar foobaz fooqux"

Replacing First Match From Multiple Patterns Using preg_replace() :

The first argument to the preg_replace() function can either be a string pattern or an array of string patterns. If an array of patterns is provided then to replace the first match of each pattern you can do the following:

$replaceWith = ''; echo preg_replace(['/foo/', '/baz/'], $replaceWith, $str, 1); // output: "bar foo fooqux"

Using substr_replace()

The substr_replace() function has the following syntax:

// PHP 4+ substr_replace($string, $replacement, $startOffset, $length);

The last two parameters of the substr_replace() function (i.e. the starting offset of the match and the length of the portion of string which is to be replaced) can be used to ensure only the whole string (that’s of concern to us) is replaced, and only once. Consider the following example:

$replaceWith = ''; $findStr = 'foo'; $pos = strpos($str, $findStr); if ($pos !== false) < $str = substr_replace($str, $replaceWith, $pos, strlen($findStr)); >echo $str; // output: "bar foobaz fooqux"

Using implode() and explode()

Using the third argument to the explode() function, you can ensure you only split the string once at the first match. Consider the following (complete) syntax of the explode() function:

// PHP 4+ explode($separator, $str, $limit);

When a positive value is supplied as the $limit, the returned array will contain a maximum of $limit elements with the last element containing the rest of string. For example, if limit is set to 2 , then the returned array will contain ONE matching element with the last element containing the rest of the string.

With that knowledge, consider the example below:

$replaceWith = ''; $findStr = 'foo'; print_r(explode($findStr, $str, 2)); // output: Array ([0] => "" [1] => "bar foobaz fooqux")

Now with that result, you can simply use implode() to join the string back using the replace-with value like so:

$replaceWith = ''; $findStr = 'foo'; echo implode($replaceWith, explode($findStr, $str, 2)); // output: "bar foobaz fooqux"

Hope you found this post useful. It was published 01 Jul, 2018 (and was last revised 03 Jun, 2021 ). Please show your love and support by sharing this post.

Источник

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