Home >Backend Development >PHP Problem >How to delete specified characters from a string in php
PHP is a widely used programming language that can be used to build a variety of applications. In many cases, we need to remove specified characters or some special characters from strings. This article will introduce how to use PHP to remove specified characters from a string.
Delete a single character in a string
In PHP, a single character can be removed using the string functions str_replace()
, preg_replace()
and substr()
and other functions to delete. The usage of these functions is as follows:
Use the str_replace() function to delete a single character:
$str = "Hello, World!"; $char = ","; $new_str = str_replace($char,'',$str); echo $new_str;
Output:
Hello World!
In the above code, str_replace()# The ## function will find a comma (
,) in a string and replace it with an empty string, thereby removing it.
$str = "Hello, World!"; $char = "/[,\s]/"; $new_str = preg_replace($char,'',$str); echo $new_str;Output:
HelloWorld!In the above code, the
preg_replace() function uses regular expressions to find commas (
,) and spaces (
\s) and replace them with empty strings, thereby removing these characters.
$str = "Hello, World!"; $char = ","; $pos = strpos($str,$char); if($pos!==false){ $new_str = substr_replace($str,'',$pos,1); echo $new_str; }Output:
Hello World!In the above code, the
substr_replace() function is used to replace the specified characters are replaced with an empty string. Use the
strpos() function to find the character position you want to remove, then use
substr_replace() to replace it with an empty string.
str_replace()or
preg_replace() function. These functions take an array as the first argument, the target character or string as the key, and the string to replace as the value. This can delete multiple characters in a string in batches.
$str = "abcdefg"; $chars = array("b", "d", "f"); $new_str = str_replace($chars, '', $str); echo $new_str;Output:
acegIn the above code, the
str_replace() function uses an array , containing the characters
b,
d,
f that need to be deleted, and then replacing them with empty strings to delete these characters.
$str = "abcdefg"; $chars = "/[bdf]/"; $new_str = preg_replace($chars, '', $str); echo $new_str;Output:
acegIn the above code, the
preg_replace() function uses regular expressions The formula
/[bdf]/ matches the characters that need to be deleted and replaces them with an empty string to delete these characters.
str_replace(),
preg_replace() and
substr() functions to delete a single character, or we can use these functions to delete multiple characters in batches. In actual projects, we need to choose the appropriate method based on specific needs.
The above is the detailed content of How to delete specified characters from a string in php. For more information, please follow other related articles on the PHP Chinese website!