Home > Article > Backend Development > How to remove non-alphanumeric characters from string in PHP? (code example)
In PHP, you can use the preg_replace() function to use regular expressions to delete non-alphanumeric characters in a string. The following article will introduce to you how the preg_replace() function deletes non-alphanumeric characters in a string. I hope it will be helpful to you.
preg_replace() function
First let’s take a look at the preg_replace() function.
The preg_replace() function can execute a regular expression to search or replace strings of all symbol conditions through the rules defined by this regular expression.
Basic syntax:
preg_match( $pattern, $replacement_string, $original_string )
Parameters:
$pattern parameters: Regular expression, indicating the rules for searching and replacing in strings.
$replacement_string parameter: Indicates the string used for replacement.
$original_string parameter: Indicates the original string that needs to be searched or replaced.
Return value:
1. When a match is found and replaced, the modified string will be returned.
2. If no match is found, the original string remains unchanged and returned as is.
Delete non-alphanumeric characters in the string
Let’s take a simple look at how the preg_replace() function deletes of non-alphanumeric characters in a string.
Example 1: Use the regular expression '/[\W]/'Match all non-alphanumeric characters and replace them with '' (empty string).
<?php $str="$#*@php中文网,2018-12-29!"; echo("原字符串:<br>"); echo($str); echo("<br><br>"); $str = preg_replace( '/[\W]/', '', $str); echo("修改后的字符串:<br>"); echo($str); ?>
Note: In regular expressions, W is a metacharacter preceded by a backslash (\W), which is used to give the combination special meaning. It represents a combination of non-alphanumeric characters.
Output:
Example 2: Match using regular expression '/[^ a-z0-9]/i' All non-alphanumeric characters and replace them with '' (empty string).
<?php $str="$#*@www.php.cn!2018-12-29?"; echo("原字符串:<br>"); echo($str); echo("<br><br>"); $str = preg_replace( '/[^a-z0-9]/i', '', $str); echo("修改后的字符串:<br>"); echo($str); ?>
Output:
Description: In the regular expression '/[^ a-z0-9]/i'
1. i: used for case insensitivity.
2. az: It is used for all lowercase letters. Because i has been mentioned in the statement (not case-sensitive), there is no need to specify AZ.
3, 0-9: used to match all numbers.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to remove non-alphanumeric characters from string in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!