Home  >  Article  >  Backend Development  >  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

青灯夜游
青灯夜游Original
2021-07-15 15:22:523881browse

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));

?>

Output:

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

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)

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!

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