Home>Article>Backend Development> How to keep only letters in php string

How to keep only letters in php string

青灯夜游
青灯夜游 Original
2022-08-29 19:44:00 2730browse

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])".

How to keep only letters in php string

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)

How to keep only letters in php string

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)
##Parameter Description 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. Required. Arrays to be combined into strings.
$glue
$arr
#implode() function returns a string composed of array elements and the "$glue" character.

How to keep only letters in php string

Recommended learning: "

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!

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