Skip to content

[PHP] Use “str_replace()” Function to Replace the String

If we want to replace some content of a string (it is a common thing), we can use str_replace() to do it.


Introduction of str_replace()

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

There are three parameters we need to pass:

  • $search: string pattern we want to match
  • $replace: the new string that will replace the old content
  • $subject: the full string

These three parameters can be a series or array containing a string. The last $count is very simple replacement. For example, set it to 1, it means just replaced once and then on longer replace.

If you need to find the matching string form, you need a regular expression matching, you can use preg_replace().

If the matching string you need to find is not sensitive to the case (that is, it’s directly matched with the form of a lower or upper case), then you can use str_ireplace().


Sample Code

The following is a easiest sample code:

$text = "Hello World!";
$new_text = str_replace("World", "Clay", $text);
print_r($new_text);


Output:

Hello Clay!

References


Read More

Tags:

Leave a Reply