|
|
 |
trim (PHP 3, PHP 4, PHP 5) trim --
Strip whitespace (or other characters) from the beginning and end of a string
Descriptionstring 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.
You can also specify the characters you want to strip, by means
of the charlist parameter.
Simply list all characters that you want to be stripped. With
.. you can specify a range of characters.
Example 1. Usage example of trim() |
<?php
$text = "\t\tThese are a few words :) ... ";
echo trim($text); echo trim($text, " \t."); $clean = trim($binary, "\x00..\x1F");
?>
|
|
Note:
The optional charlist parameter was
added in PHP 4.1.0
See also ltrim() and rtrim().
User Contributed Notes
trim
dmr37 at cornell dot edu
17-May-2005 02: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
30-Mar-2005 09: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
29-Mar-2005 01: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.
04-Mar-2005 12: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
16-Feb-2005 12: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
07-Feb-2005 06: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 09: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 06: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
26-May-2004 04: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 08: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
16-Jul-2003 04: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
02-Jul-2003 07: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
05-Jun-2003 08: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
02-Jun-2003 12: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
25-Apr-2003 05: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
30-Jan-2003 05: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
03-Jun-2002 01: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
26-May-2002 12: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
19-Mar-2002 11: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
14-Mar-2002 01: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
$my_string = "Liquid\r\nTension Experiment\r\n\r\n\r\n";
$my_wonderful_string = str_replace("\r\n", " ", $my_string);
$my_wonderful_string = str_replace("\r\n", "", $my_string);
?>
thibs at thibs dot com
16-Oct-2001 10: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
13-Dec-2000 10:02
To replace all excess white spaces with a single space try:
print $pizza = "One Two Three Four";
$pizza = eregi_replace("[[:space:]]+", " ", $pizza);
13-Oct-2000 04:25
To compact any number of spaces inside a string to a single space, use the following code:
print $pizza = "Teil1 Teil2 Teil3 Teil4 Teil5 Teil6 df\n";
$pizza = ereg_replace (' +', ' ', $pizza);
alivesay at yellowbrix dot com
24-Jul-2000 08: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
]
| |