Home > Backend Development > PHP Problem > How to remove extra characters at the beginning and end of a string in PHP

How to remove extra characters at the beginning and end of a string in PHP

autoload
Release: 2023-03-09 10:58:01
Original
2408 people have browsed it

How to remove extra characters at the beginning and end of a string in PHP

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 )
Copy after login
  • $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 :) ..."
?>
Copy after login

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 :) ..."
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template