Home>Article>Backend Development> How to keep only letters in php string
Implementation steps: 1. Use the preg_match_all() function with regular expressions to filter strings and retain only English letters. The syntax is "preg_match_all("/[a-zA-Z]/u","$str ",$arr);", the letters will be stored in the "$arr" array; 2. Use the implode() function to splice the result value into a new string, the syntax is "implode($arr[0])".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the preg_match_all() function and implode() function to make the string contain only letters.
Implementation steps:
Step 1: Use the preg_match_all() function with regular expressions to filter strings and only retain English letters
The preg_match_all() function matches all occurrences of the pattern in the string.
preg_match_all (pattern , subject ,matches,flags,offset);
pattern:: The pattern to be searched, in string form.
subject: Input string.
matches: multi-dimensional array, output all matching results as output parameters, array sorting is specified by flags.
#flags: Array result sorting, can be used in combination with the following flags
offset: Usually, search starts from the beginning of the target string position starts. (Unit is bytes)
As you can see, the result is a two-dimensional array.
The required English letters are in the internal sub-array$arr[0]
, just convert it into a string.
Step 2: Use the implode() function to splice the result value into a string
The implode() function can convert a one-dimensional array into a string. The syntax is as follows:
implode($glue,$arr)
Description | |
---|---|
$glue | Optional. Used to set a string, indicating that $glue is used to connect each element of the array together. By default, $glue is an empty string.|
$arr | Required. Arrays to be combined into strings.
PHP Video Tutorial"
The above is the detailed content of How to keep only letters in php string. For more information, please follow other related articles on the PHP Chinese website!