String
is a common format for php
to obtain the value of form elements. Because users may generate redundant data when inputting data daily. characters, such as carriage return, line feed, tab, ordinary space characters, etc. How to solve these problems, trim()
will come into play.
First, let’s take a look at how to use the trim()
function:
trim ( string $str , string $character_mask )
$str: The string to be processed.
$character_mask: optional, the value can be set to the string that needs to be filtered, the default value is "
" (normal space character), " \t
" (tab character), "\n
" (line feed character), "\r" (carriage return character), "\0
" (null character), "\x0B
" (vertical tab character).
Actual usage:
If the second parameter is empty, the " " (ordinary space characters), " at the beginning and end of $text1
will be \t
" (tab character), "\n
" (line feed character), "\r
" (carriage return character), " \0
" (null character) and "\x0B
" (vertical tab character) are removed, and a new deleted string is returned.
<?php $text1 = "\t\tThese are a few words :) ... \n"; var_dump($text1); //string(33) " These are a few words :) ... " var_dump(trim($text1)); //string(28) "These are a few words :) ..." ?>
If the second parameter is set to the value "\t
", as above, the content containing "\t
" at the beginning and end of the string will be removed and returned A new string after deletion.
<?php $text1 = "\t\tThese are a few words :) ... \n"; var_dump($text1); //string(33) " These are a few words :) ... " var_dump(trim($text1,"\t")); //string(28) "These are a few words :) ..." ?>
If you only need to delete the specified string from the left side of the string, use ltrim()
If you only need to delete the specified string from the left side of the string, use rtrim()
Recommended: 《2021 PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of How to remove extra characters at the beginning and end of a string in PHP. For more information, please follow other related articles on the PHP Chinese website!