Current Location: Home> Latest Articles> Detailed Guide to Replacing English Periods with Other Characters in PHP

Detailed Guide to Replacing English Periods with Other Characters in PHP

gitbox 2025-06-27

Introduction to str_replace Function in PHP

In PHP, the str_replace() function is a built-in method used to replace specified characters or substrings within a string. It supports replacement of single characters or strings, as well as batch replacements using arrays.

Parameters of str_replace Function

The basic syntax of the function is as follows:

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

Where $search is the character or substring to be replaced, which can be a string or an array; $replace is the replacement string or array; $subject is the string to be processed; and $count is an optional parameter to return the number of replacements made.

Example of String Replacement

For example, replacing "world" with "everyone" in a string:

$str = "hello world!";
echo str_replace("world", "everyone", $str);

Output:

<span class="fun">hello everyone!</span>

Replacing English Period with Space

If you want to replace an English period (".") with a space, use:

$str = "I am a PHP coder. How about you?";
echo str_replace(".", " ", $str);

After execution, the output is:

<span class="fun">I am a PHP coder  How about you?</span>

The period is replaced by a space.

Replacing English Period with Other Characters

You can also replace the period with other characters, like a comma:

$str = "I am a PHP coder. How about you?";
echo str_replace(".", ",", $str);

The output is:

<span class="fun">I am a PHP coder, How about you?</span>

Handling Multiple Punctuation Replacements

If you need to replace multiple characters at once, you can use arrays for $search and $replace:

$str = "I am a PHP coder. How about you? Nice weather today.";
$search = array(".", "?");
$replace = array(",", "!");
echo str_replace($search, $replace, $str);

Output:

<span class="fun">I am a PHP coder, How about you! Nice weather today,</span>

This replaces both periods and question marks simultaneously.

Conclusion

The PHP str_replace function offers a simple and efficient way to replace English periods with any desired characters, whether replacing a single period or multiple punctuation marks. It is a flexible and powerful tool for string manipulation.