 |
trim (PHP 3, PHP 4, PHP 5) trim -- Strip whitespace (or other characters) from the beginning and end of a string 说明string trim ( string str [, string charlist] )
This function returns a string with whitespace stripped from the
beginning and end of str.
Without the second parameter,
trim() will strip these characters:
" " (ASCII 32
(0x20)), an ordinary space.
"\t" (ASCII 9
(0x09)), a tab.
"\n" (ASCII 10
(0x0A)), a new line (line feed).
"\r" (ASCII 13
(0x0D)), a carriage return.
"\0" (ASCII 0
(0x00)), the NUL-byte.
"\x0B" (ASCII 11
(0x0B)), a vertical tab.
参数
- str
The string that will be trimmed.
- charlist
Optionally, the stripped characters can also be specified using
the charlist parameter.
Simply list all characters that you want to be stripped. With
.. you can specify a range of characters.
范例
例子 1. Usage example of trim()
<?php
$text = "\t\tThese are a few words :) ... ";
echo trim($text); // "These are a few words :) ..." echo trim($text, " \t."); // "These are a few words :)"
// trim the ASCII control characters at the beginning and end of $binary // (from 0 to 31 inclusive) $clean = trim($binary, "\x00..\x1F");
?>
|
|
例子 2. Trimming array values with 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"
} |
|
rchaube at staff dot atlantic dot net
19-Feb-2006 05:03
I was accepting text pasted from a csv file into a textarea in my code. I found that even using trim was not able to get rid of the whitespace characters at the end of the string.
Finally, using this helped:
$result = trim($source,"\x7f..\xff\x0..\x1f");
Hope this saves someone few hours. All thanks to previous comment from HW for this
jonathan at abbett dot org
27-Jan-2006 01:07
With all this talk about trimming array values, it should be known that accidentally using the trim() function with an array() argument ...
<?php
$array = array(1, 2, 3);
$array = trim($array);
print_r($array); // prints "Array"
echo($array); // also prints "Array"
?>
... yields the string "Array"
asharm4 at ilstu dot edu
18-Jan-2006 01:30
This staetment removes the trailing and leading whitespaces from the string..Really useful when handling the form values submitted by a visitor or analyzing a log file.
$trimmed_string = preg_replace ( "/\s\s+/" , " " , $untrimmed_string );
Note : thsi would only remove leading and trailing whitespaces. For the whitespaces in the string use any of the above methods.
Martin Kealey
15-Dec-2005 06:10
Using "trim" to minimize the format of a decimal number strikes me as awkward. I would just use:
$str += 0;
This even has the added benefit of ensuring that you have at least one digit (and thus have a valid number) even if the original was empty.
warhog at warhog dot net
08-Dec-2005 04:28
I was wondering about much of the examples given below, but the current (2005-12-07) function definition in the manual is not correct.
The function trim is defined as
trim(string string [, string charlist])
you must give the string-parameter and you can optionally add a parameter charlist - these chars are the chars to strip from the beginning and the end of the file.
(its self-evident that the default of this parameter is "\n\t\r\h\v\0 ")
hope that'll help - and that the docs are updated.. i don't know since which php-version that optional parameter can be used - i know that it works with PHP >= 4.3 & >= 5.0 . Maybe it's beeing there since 10 years and just an enormous insider :-)
davis_utah at yahoo dot com
02-Sep-2005 02:30
Just a word of caution when looping through a batch of strings (in the thousands or more). Using trim to take off a left over character (like a comma in a csv output) will result in a much slower execution. It is better to use a tiny bit of conditional logic instead.
I believe the reason this is the case is because of having to create a new spot in memory to temporarily handle the result of trim.
Hope this helps.
rifter at cox dot net
16-Jul-2005 03:49
Chris wrote:
> Here's a neat function to trim off extraneous zeros and the > decimal, leaving important numbers intact:
> ...
Actually use:
<?php
...
return rtrim(trim($num, '0'), '.');
...
?>
This ensures that a left leading decimal place doesn't get removed i.e. 00.010 should return .01 and not 01.
chris dot cowart at gmail dot com
06-Jul-2005 01:20
Here's a neat function to trim off extraneous zeros and the decimal, leaving important numbers intact:
<?php
function clean_num($num){
return trim(trim($num, '0'), '.');
}
echo clean_num('06000.3050');
echo clean_num('500.00');
?>
Output:
6000.305
500
I find it very handy to use when pulling data from decimal fields in MySQL and putting them into <input> fields. Makes everything cleaner :)
ervin dot kosch at gmail dot com
16-Jun-2005 10:25
I find that when I use the explode() function to break apart string that read from a text file it sometime leave LF or CR that mess up my text processing. So I wrote this function to get rid of any white spaces or CF/LF that might be causing a problem.
I have had some people report problems in older versions of PHP4.
<?
function utrim($source){
$temp = ltrim($source);
$temp = rtrim($temp);
$temp = trim($temp);
return $temp;
}
?>
15-Jun-2005 12:54
here's a heads up folks.
in the event that you want to check the result of a trim for being empty the following code fails::
$emptyvar = " ";
if ( empty(trim($emptyvar)) )
{
echo "It was empty";
}
this code works as expected::
$emptyvar = " ";
$check = trim($emptyvar);
if ( empty($check) )
{
echo "It was empty";
}
okumurya at hotmail dot com
05-Jun-2005 07:01
fread/fwrite blocks program when no data available.
so, you consider use select system call.
following is example.
<?php
/**
*
* write/read pipe
*
* @param resource $w_fp write file handle
* @param resource $r_fp read file handle
* @param string $input
* @return string
*/
function _writeread_pipe(&$w_fp, &$r_fp, $input) {
$output = '';
$write_bytes = 0;
//
while (True) {
if (!isset($r_fp) && !isset($w_fp)) break;
$read = isset($r_fp) ? array($r_fp) : Null;
$write = isset($w_fp) ? array($w_fp) : Null;
// select pipes
$r = stream_select($read,
$write,
$except = Null,
30
);
if ($r === False) {
return PEAR::raiseError('process timeout');
}
// read pipe
if (isset($read) && isset($read[0])) {
do {
$buf = fread($r_fp, 1024);
if (strlen($buf) == 0) {
fclose($r_fp);
$r_fp = Null;
break;
}
$output .= $buf;
} while (True);
}
// write pipe
if (isset($write) && isset($write[0])) {
$r = fwrite($w_fp, substr($input, $write_bytes));
if ($r === False) {
return PEAR::raiseError('process write error');
}
$write_bytes += $r;
if ($write_bytes == strlen($input)) {
fclose($w_fp);
$w_fp = Null;
}
}
}
return $output;
}
?>
thom at xmods dot hu
24-May-2005 04:54
Hi everybody.
I make a registration page, and i want to drop \ t \n \r ...etc.
I send the trim function to the post but the trim not work good because if i send the post with \ t or \ r or \n it's work but later i have got an empty registration.
Here is the code:
$fullname = trim($_POST['regfullname']);
$messenger = trim($_POST['regmsn']);
$nick = trim($_POST['regnick']);
$telefon = trim($_POST['regtel']);
$email = trim($_POST['regemail']);
$www = trim($_POST['regwww']);
$pass1 = trim($_POST['regpassword1']);
$pass2 = trim($_POST['regpassword2']);
$icq = trim($_POST['regicq']);
$signature = trim($_POST['regsignature']);
$config = trim($_POST['regconfig']);
$protect = array(
"<" => "<",
">" => ">",
"&" => "&",
"\"" => """,
"'" => "'",
"\n" => " ",
"\t" => " ",
"\r" => " ",
"\0" => " ",
"\x0B" => "",
" " => ""
);
$protectmail = array(
"@" => "(KUKAC)",
"." => "(PONT)"
);
$fullname = strtr($fullname, $protect);
$messenger = strtr($messenger, $protect);
$nick = strtr($nick, $protect);
$telefon = strtr($telefon, $protect);
$email = strtr($email, $protectmail);
$www = strtr($www, $protect);
$pass1 = strtr($pass1, $protect);
$pass2 = strtr($pass2, $protect);
$icq = strtr($icq, $protect);
$signature = strtr($signature, $protect);
$config = strtr($config, $protect);
dmr37 at cornell dot edu
18-May-2005 03:47
Note that manithu's post on 29-Mar-2005 02:49 for identifying strings that only contain whitespaces will also identify strings like "0" and " 0 " as being empty. If you want to check whether something ONLY has whitespaces, use the following:
<?php
if (trim($foobar)=='') {
echo 'The string $foobar only contains whitespace!';
}
?>
admin at semaster dot ru
31-Mar-2005 11:37
Another recursive trim function for multi-dimensional arrays ( uses only trim function :)
function array_trim($arr, $charlist=null){
foreach($arr as $key => $value){
if (is_array($value)) $result[$key] = array_trim($value, $charlist);
else $result[$key] = trim($value, $charlist);
}
return $result;
}
manithu
30-Mar-2005 03:49
An faster (and eleganter) way than using regular expressions to check if a string only contains whitespaces is to use trim().
Example:
<?php
if (!trim($foobar)) {
echo 'The string $foobar is empty!';
}
?>
I hope this helps somebody.
05-Mar-2005 02:25
It is important to stress that trim() only removes whitespace characters from the *beginning* and *end* of str. To remove whitespace characters embedded within a string (newlines, for instance) you can use str_replace(), searching for and destroying both \n and \r characters.
Rook
17-Feb-2005 02:29
Recursive trim function for multi-dimensional arrays:
<?php
function trim_array($x)
{
if (is_array($x)) {
return array_map('trim_array', $x);
}
return trim($x);
}
$_POST = array_map('trim_array', $_POST);
?>
Hayley Watson
08-Feb-2005 08:46
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
abderzack host provider hotmail dot com
12-Nov-2004 11:44
To eliminate all the empty strings from my array, I used the array_filter, that way :
1.
I defined a function returning true iff the passed as parameter string is NOT empty.
function notEmpty($string)
{
return !empty($string);
}
2.Use array filter :
$myarray = array_filter($myarray ,"notEmpty");
That's it.
Of course, if you want to prove your mama you can write unreadable code, you can create an anonymous function, by using the create_function, instead of declaring the function notEmpty.
Hope that will help you.
root at andthesito dot net
06-Oct-2004 07:33
About trim all elements in an array.
May be
array_walk($db ,create_function('&$arr','$arr=trim($arr);'));
could be better than :
foreach ($db as $key=>$value) { $db[$key]=trim($value); }
webmaster __AT__ digitalanime __DOT__ nl
27-May-2004 05:50
To:
mrizzo at advancedsl dot com dot ar
And what about array_map()? :)
<?php
$myarray = array(
'hello' => ' bye ',
'hey' => ' howdie',
'haai' => ' today'
);
array_map('trim', $myarray);
?>
:)
jubi at irc dot pl
20-Apr-2004 09:48
To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:
<?
$text = preg_replace('/\s+/', ' ', $text);
?>
------------
JUBI
http://www.jubi.buum.pl
mrizzo at advancedsl dot com dot ar
17-Jul-2003 05:00
About trim all elements in an array.
array_filter($db, 'trim') doesn't work becouse it does NOT modify array's elements, it only returns a copy from those elements which return true on the callback function.
I think that:
foreach ($db as $key=>$value) { $db[$key]=trim($value); }
still being the best option.
rwelti at yahoo dot com
03-Jul-2003 08:45
Regarding the editor's note to rhelic above about how to trim all elements in an array:
I wanted a perl "chomp" of newlines for all elements in an array.
I tried array_filter for a long time, but rhelic's straightforward way is what worked.
// chomp newlines off all elements in stations array
$stations = array_filter($stations, 'trim'); // editor's way - nope
foreach ($stations as $key => $value) {
$stations[$key] = trim($value); } // works fine
using PHP 4.3.1 on Solaris
HW
06-Jun-2003 09:32
You can combine character ranges and individual characters in trim()'s second argument (ditto for ltrim and rtrim). All of the specified characters and ranges will be used concurrently (i.e., if a character on either end of the string matches any of the specified charaters or character ranges, it will be trimmed). The characters and character ranges can be in any order (except of course that the character ranges need to be specified in increasing order) and may overlap.
E.g., trim any nongraphical non-ASCII character:
trim($text,"\x7f..\xff\x0..\x1f");
olivierdsm at hotmail dot com
03-Jun-2003 01:42
I just wanted to say that when you want to do a LDAP query based on a form value (i mean something like : <form method="POST" action="script_createnewticket.php" name="demande2">) dynamicaly updated from a popup javascript , (for example <a onclick=" opener.document.forms['demande2'].elements['thename3'].value='my name') it doesn't work.
It took me 2 days to find out that when you use trim, to "convert" the value, then it works.
-------------------------
$thename4=trim($thename3);
$ds=ldap_connect("$myldapserver"); // connects to the LDAP SERVER
if (!($ds = ldap_connect("$myldapserver") ) ) {
die ("Could not connect to LDAP server");
}
$r=ldap_bind($ds, "cn=".$NTusername, $NTpassword);
$sr = ldap_search($ds, ' ', "uid=".$thename4);
$info = ldap_get_entries($ds, $sr);
-------------------------------------
only on this case you will get results.
Strange and good to know
bishop
26-Apr-2003 06:56
[Editor: I botched my last note; please delete and use this one]
Non-breaking spaces can be troublesome with trim (as per an earlier comment):
// turn some HTML with non-breaking spaces into a "normal" string
$myHTML = " abc";
$converted = strtr($myHTML, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted = trim($converted);
// are translated to 0xA0, so use:
$converted = trim($converted, "\xA0");
// PS: Thanks to John for saving my sanity!
Joshua dot Logsdon at ohiou dot edu
31-Jan-2003 07:51
In response to the line mentioned above...
$clean = trim($binary,"\0x00..\0x1F");
I was also able to get
$clean = trim($binary,"\0x00-\0x1F");
to function.
daggillies at yahoo dot com
04-Jun-2002 02:57
NOTE:
All the above examples using ereg_replace with an escape code of \v are BROKEN! \v is NOT an escape code in PHP. Using a regexp of \v e.g.
$str=ereg_replace("[\r\t\n\v]","",$str);
will remove any instances of the letter 'v' from your string. So 'Activity' becomes 'Actiity'. Probably not what you want.
Here is a small function I use to strip whitespace from the end of strings and squash repeated whitespace down to a single space in the middle of strings:
function wsstrip(&$str)
{
$str=ereg_replace (' +', ' ', trim($str));
$str=ereg_replace("[\r\t\n]","",$str);
}
David Gillies
San Jose
Costa Rica
j dot metzger at steptown dot com
27-May-2002 01:21
Be careful when you use the charlist with the hex-codes...
use e.g. \x22 instead of \0x22 (this last thing won't work).
An example to strip quotes ' " ' (double quotes) and " ' " (single quotes) is to do this:
$example[0]='"hello"';
$example[1]="'baby'"
foreach ($example as $key => $val)
$example[$key]=trim($val,"\x22\x27");
# this works brilliant, but be aware:
# $example[$key]=trim($val,"\0x22\0x27");
# won't work !!!
-> tested on php 4.2.1
REMOVETHISNOSPAMkilling at bluecarrots dot com
20-Mar-2002 01:30
If you want to totally stop windows (dunno about other os's) peeps from adding spaces (say, you need to check there name against a special one to stop impersonations) use this:
$nick = ereg_replace("[\r\n\t\v\ ]", "", trim($nick));
It has the alt code 0160 added to it
tbm.at.home.dot.nl
15-Mar-2002 03:30
Windows uses two characters for definining newlines, namely ASCII 13 (carriage return, "\r") and ASCII 10 (line feed, "\n") aka CRLF. So if you have a string with CRLF's, trim() won't recognize them as being one newline. To solve this you can use str_replace() to replace the CRLF's with with a space or something.
<?php
// string with bunch of CRLF's
$my_string = "Liquid\r\nTension Experiment\r\n\r\n\r\n";
// replace CRLF's with spaces
$my_wonderful_string = str_replace("\r\n", " ", $my_string);
// would result in "Liquid Tension Experiment "
// or just delete the CRLF's (by replacing them with nothing)
$my_wonderful_string = str_replace("\r\n", "", $my_string);
// would result in "LiquidTension Experiment"
?>
thibs at thibs dot com
16-Oct-2001 11:16
[Editor's Note:
ltrim() is a better choice for this task. You can also use rtrim() to trim from the end of the string.
--zak@php.net]
To erase space just at the beginning of the string, use :
$string = eregi_replace("^[[:space:]]+", "", $string);
cgi at harrison dot org
14-Dec-2000 12:02
To replace all excess white spaces with a single space try:
print $pizza = "One Two Three Four";
$pizza = eregi_replace("[[:space:]]+", " ", $pizza);
14-Oct-2000 05:25
To compact any number of spaces inside a string to a single space, use the following code:
print $pizza = "Teil1Teil2Teil3Teil4Teil5Teil6df\n";
$pizza = ereg_replace (' +', ' ', $pizza);
alivesay at yellowbrix dot com
25-Jul-2000 09:35
If you are trying to take out whitespace from the middle of a string, you need to use a different function, str_replace:
<PRE>str_replace(" ", "", "United Kingdom);</PRE>
[Editor's note:
This strips *all* spaces present in the string, not just the ones in the middle
]
|  |