runoops.com

PHP trim() 函数

(PHP 4, PHP 5, PHP 7)

trim — 去除字符串首尾处的空白字符(或者其他字符)

定义和用法

trim() 函数移除字符串两侧的空白字符或其他预定义字符。

相关函数:

  • ltrim() - 移除字符串左侧的空白字符或其他预定义字符
  • rtrim() - 移除字符串右侧的空白字符或其他预定义字符

语法

trim(string,charlist)
参数 描述
string 必需。规定要检查的字符串。
charlist

可选。规定从字符串中删除哪些字符。如果被省略,则移除以下所有字符:

  • "\0" - NULL
  • "\t" - 制表符
  • "\n" - 换行
  • "\x0B" - 垂直制表符
  • "\r" - 回车
  • " " - 空格

范例

Example #1 trim() 使用范例

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

结果:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"

Example #2 使用 trim() 清理数组值

<?php
function trim_value(&$value) 
{ 
    $value = trim($value); 
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

结果:

array(3) { [0]=> string(5) "apple" [1]=> string(7) "banana " [2]=> string(11) " cranberry " } array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(9) "cranberry" }