How do I replace a string in PHP?

To replace a substring in a PHP string with another string, use the str_replace($search, $replace, $subject, $count = null) function. The str_replace() function takes the search value as the first argument, the replacement value as the second argument, and the string to replace as the third argument. The str_replace() function does not modify the supplied string; instead, it returns a copy of the string in which all occurrences of the search value are replaced with the replacement value. To replace multiple search values with multiple replacement values at once, you can pass an array of those values in the $search and $replace arguments instead of strings. To limit the number of substitutions performed, pass the max value in the optional $count argument. Alternatively, you can replace the string using PHP Regular Expressions, but you should prefer str_replace() over preg_replace() unless you need advanced replacement rules. In this PHP string replacement example, we replace all occurrences of search strings with the new value. Click Execute to run PHP String Replace Example online and see the result.
How do I replace a string in PHP? Execute
  echo str_replace("hard", "easy", "Replacing a string in PHP is hard." );
Updated: Viewed: 1336 times