How to use the PHP function for character replacement?

There are many character replacement functions available in PHP, with commonly used functions being str_replace() and preg_replace().

  1. Replace characters using the str_replace() function.
$string = "Hello, world!";
$new_string = str_replace("Hello", "Hi", $string);
echo $new_string; // Output: Hi, world!
  1. Perform regular expression replacement using the preg_replace() function.
$string = "Hello, world!";
$new_string = preg_replace("/\bworld\b/", "universe", $string);
echo $new_string; // Output: Hello, universe!

These are two common methods of character replacement, choose the one that best fits your needs for character replacement.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds