PASSWORD RESET

Your destination for complete Tech news

PHP

How to replace a string in PHP?

399 0
< 1 min read

To replace a string in PHP, you can use the str_replace function. This function performs a search and replace operation on a string, replacing all occurrences of the search string with the replacement string.

Here’s an example of how you can use it:

$str = 'Hello world';
$new_str = str_replace('world', 'PHP', $str);
echo $new_str;  // Outputs: Hello PHP

You can also use the str_replace function to replace multiple strings at once, by providing arrays of search and replacement strings:

$str = 'Hello world';
$search = ['Hello', 'world'];
$replace = ['Hi', 'PHP'];
$new_str = str_replace($search, $replace, $str);
echo $new_str;  // Outputs: Hi PHP

Note that the str_replace function is case-sensitive by default. If you want to perform a case-insensitive search and replace, you can use the str_ireplace function instead.

$str = 'Hello world';
$new_str = str_ireplace('world', 'PHP', $str);
echo $new_str;  // Outputs: Hello PHP

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.