Home  >  Article  >  Backend Development  >  PHP removes numbers from Chinese characters

PHP removes numbers from Chinese characters

王林
王林Original
2023-05-06 11:19:07608browse

When using PHP to process Chinese strings, sometimes we need to remove the numbers in Chinese characters. This problem is relatively common. This article will introduce how to use PHP to remove numbers from Chinese characters.

1. Use regular expressions to remove numbers from Chinese characters

In PHP, we can use regular expressions to remove numbers from Chinese characters. The following is a simple sample code:

$str = "这是一个带有数字1和2的句子";
$str = preg_replace('/\d+/u', '', $str);
echo $str;

In the above code, we use the preg_replace() function to replace the numbers in the string with an empty string, and finally output the replaced string.

Among them, the regular expression "\d" means matching one or more numbers, and the parameter "u" means processing the string in UTF-8 encoding.

2. Use the substr() function to remove numbers from Chinese characters

In addition to using regular expressions, we can also use the substr() function to remove numbers from Chinese characters. The following is a sample code:

$str = "这是一个带有数字1和2的句子"; 
$newStr = "";
for($i=0;$i<strlen($str);$i++){
    $char = substr($str,$i,1);
    if(ord($char)<0x80 || !is_numeric($char)) {
        $newStr .= $char;
    }
}
echo $newStr;

In the above code, we traverse each character in the string. If the ASCII code of the character is less than 0x80 (that is, an English letter) or is not a number, the character is added to the new in the string.

3. Use the mb_ereg_replace() function to remove numbers from Chinese characters

In addition to the above methods, we can also use the mb_ereg_replace() function to remove numbers from Chinese characters. The following is a sample code:

$str = "这是一个带有数字1和2的句子";
$str = mb_ereg_replace('[0-9]', '', $str);
echo $str;

In the above code, we use the mb_ereg_replace() function to replace the numbers in the string with an empty string, and finally output the replaced string. Among them, the regular expression "[0-9]" means matching numbers.

Summary

This article introduces how to use PHP to remove numbers from Chinese characters. We can use regular expressions, substr() function and mb_ereg_replace() function to achieve this function. In actual projects, we can choose different methods to process numbers in Chinese strings based on needs and scenarios.

The above is the detailed content of PHP removes numbers from Chinese characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn