Current Location: Home> Latest Articles> How to Replace All Characters in a String in PHP?

How to Replace All Characters in a String in PHP?

gitbox 2025-06-29

What is String Replacement?

In PHP, string replacement refers to replacing certain characters or all characters within a string with other characters or strings.

How to Replace All Characters in a String in PHP

In PHP, the str_replace function can be used to replace characters in a string. The basic syntax is as follows:

<span class="fun">str_replace(search, replace, subject, count)</span>

The parameters are explained as follows:

  • search: Required. The character or string to be replaced, which can be a single character or multiple characters.
  • replace: Required. The character or string to replace with.
  • subject: Required. The original string.
  • count: Optional. Specifies the number of replacements to make.

Replace All Characters in a String

The following example demonstrates how to use the str_replace function to replace all commas in a string with spaces:

$str = "Hello, world!";
$new_str = str_replace(",", " ", $str);
echo $new_str; // Output: Hello  world!

Use Regular Expressions to Replace All Characters in a String

If you need to use regular expressions to replace all characters in a string, you can use the preg_replace function. The basic syntax is as follows:

<span class="fun">preg_replace(pattern, replacement, subject, limit)</span>

The parameters are explained as follows:

  • pattern: Required. The regular expression pattern.
  • replacement: Required. The string to replace with.
  • subject: Required. The original string.
  • limit: Optional. Specifies the number of replacements to make.

The following example demonstrates how to use the preg_replace function to replace all characters in a string with asterisks:

$str = "Hello, world!";
$new_str = preg_replace("/./", "*", $str);
echo $new_str; // Output: ***********

Conclusion

In PHP, string replacement can be done using the str_replace or preg_replace functions. With these two methods, you can flexibly replace characters within a string. When using regular expressions, more complex replacement logic can be achieved.