replace a substring in a string in php

To replace a substring in a string in PHP, you can use the built-in str_replace() function.

Syntax:

main.php
str_replace($search, $replace, $subject);
42 chars
2 lines

Parameters:

  • $search - the substring to be replaced
  • $replace - the new substring to replace the old substring
  • $subject - the original string

Example:

main.php
$string = "hello world";
$new_string = str_replace("world", "everyone", $string);
echo $new_string;
100 chars
4 lines

Output:

main.php
hello everyone
15 chars
2 lines

In the example above, we're replacing the word "world" with "everyone" in the string "hello world".

Note that str_replace() is case-sensitive, so if you want to replace all occurrences (case-insensitive) of the substring, you can use the str_ireplace() function instead.

gistlibby LogSnag