Home > Backend Development > PHP Problem > How to remove spaces and newlines at the beginning and end of a string in php

How to remove spaces and newlines at the beginning and end of a string in php

青灯夜游
Release: 2023-03-11 15:30:02
Original
3933 people have browsed it

In PHP, you can use the trim() function to remove spaces and newlines at the beginning and end of a string. This function can remove whitespace characters (or other characters) at the beginning and end of a string. The syntax format is "trim(string) ".

How to remove spaces and newlines at the beginning and end of a string in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In PHP, you can use trim () function to remove spaces and newlines at the beginning and end of a string.

<?php
header("Content-type:text/html;charset=utf-8");
$str = " PHP中文网 \n";
echo "原字符串:";
var_dump($str);

echo "去掉首尾的空格和换行后:";
var_dump(trim($str));

?>
Copy after login

Output:

原字符串:
string &#39; PHP中文网 
&#39; (length=15)
去掉首尾的空格和换行后:
string &#39;PHP中文网&#39; (length=12)
Copy after login

Explanation:

trim() function can remove the blanks at the beginning and end of the string characters (or other characters). The syntax format is as follows:

trim(string,charlist)
Copy after login

Parameter description is as follows:

  • string: string to be processed;

  • character_mask: available Optional parameter is used to specify all characters to be removed. You can also use ".." to list a range of characters.

If the $character_mask parameter is not specified, the trim() function will remove the following characters:

  • " ": ordinary space character;

  • "\t": tab character;

  • "\n": newline character;

  • "\r": carriage return character;

  • "\0": null byte character;

  • "\x0B": vertical Tabs.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove spaces and newlines 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