The following article summarizes several php program examples for removing spaces at the beginning and end of a string in Chinese and English. Here, regular expression replacement and trim functions are used to delete the string. Let's take a look. The following article summarizes several php program examples for removing spaces at the beginning and end of a string in Chinese and English. Here, regular expression replacement and trim functions are used to delete the string. Let's take a look.
Script ec (2); script
Example 1. The trim function deletes spaces.
The trim () function is used to remove spaces at the start and end positions of a string, and returns the string with spaces removed. Syntax:
String trim (string str [, string charlist]);
The ltrim () function is used to remove spaces on the left of a string or specify a string. Syntax:
String ltrim (string str [, string charlist]);
The rtrim () function removes spaces and special characters on the right of a string. Syntax:
String rtrim (string str [, string charlist]);
The Code is as follows: |
|
$ A = "(a, B, c ,)"; Echo $ ." "; // Output: (a, B, c ,) $ B = trim ($ a, "()"); // remove the character "(" or ")" contained at the beginning and end of the string. Echo $ B ." "; // Output: a, B, c, $ C = trim ($ a, "(,)"); // remove the "(", "," or ")" characters at the beginning and end of the string. Echo $ c ." "; // Output: a, B, c ?>
|
Output result:
(A, B, c ,)
A, B, c,
A, B, c
In SQL, trim () is used to remove spaces at the beginning and end, ltrim () is used to remove spaces on the left side of the string, and rtrim () is used to remove spaces on the right side of the string.
Example 2. Use str_replace Regular Expression replacement
The Code is as follows: |
|
Function mbTrim ($ str) { Return mb_ereg_replace ('(^ (|) + | (|) + $)', '', $ str ); } |
Example 3. str_replace Regular Expression replacement
The Code is as follows: |
|
$ Str = "www.111cn.net "; $ Str = mb_ereg_replace ('^ (|) +', '', $ str ); $ Str = mb_ereg_replace ('(|) + $', '', $ str ); Echo mb_ereg_replace (''," n ", $ str ); ?> |