trim

(PHP 4, PHP 5)

trimУдаляет пробелы (или другие символы) из начала и конца строки

Описание

string trim ( string $str [, string $charlist ] )

Эта функция возвращает строку str с удаленными из начала и конца строки пробелами. Если второй параметр не передан, trim() удаляет следующие символы:

  • " " (ASCII 32 (0x20)), обычный пробел.
  • "\t" (ASCII 9 (0x09)), символ табуляции.
  • "\n" (ASCII 10 (0x0A)), символ перевода строки.
  • "\r" (ASCII 13 (0x0D)), символ возврата каретки.
  • "\0" (ASCII 0 (0x00)), NUL-байт.
  • "\x0B" (ASCII 11 (0x0B)), вертикальная табуляция.

Список параметров

str

Обрезаемая строка (string).

charlist

Можно также задать список символов для удаления с помощью необязательного аргумента charlist. Просто перечислите все символы, которые вы хотите удалить. Можно указать конструкцию .. для обозначения диапазона символов.

Возвращаемые значения

Обрезаемая строка.

Список изменений

Версия Описание
4.1.0 Добавлен необязательный параметр charlist.

Примеры

Пример #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);

$trimmed trim($hello'HdWr');
var_dump($trimmed);

// удаляем управляющие ASCII-символы с начала и конца $binary
// (от 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(9) "ello Worl"
string(14) "Example string"

Пример #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"
}

Примечания

Замечание: Возможные трюки: удаление символов из середины строки

Так как trim() удаляет символы с начала и конца строки string, то удаление (или неудаление) символов из середины строки может ввести в недоумение. trim('abc', 'bad') удалит как 'a', так и 'b', потому что удаление 'a' сдвинет 'b' к началу строки, что также позволит ее удалить. Вот почему это "работает", тогда как trim('abc', 'b') очевидно нет.

Смотрите также

  • ltrim() - Удаляет пробелы (или другие символы) из начала строки
  • rtrim() - Удаляет пробелы (или другие символы) из конца строки
  • str_replace() - Заменяет все вхождения строки поиска на строку замены

Коментарии

Автор:
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"
?>
2002-03-14 13:30:22
http://php5.kiev.ua/manual/ru/function.trim.html
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
2002-03-19 11:30:54
http://php5.kiev.ua/manual/ru/function.trim.html
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
2002-05-26 13:21:43
http://php5.kiev.ua/manual/ru/function.trim.html
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
2002-06-03 14:57:57
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2003-01-30 17:51:25
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
[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 = "&nbsp;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);

// &nbsp; are translated to 0xA0, so use:
$converted = trim($converted, "\xA0");

// PS: Thanks to John for saving my sanity!
2003-04-25 18:56:12
http://php5.kiev.ua/manual/ru/function.trim.html
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
2003-06-02 13:42:56
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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");
2003-06-05 21:32:56
http://php5.kiev.ua/manual/ru/function.trim.html
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
2003-07-02 20:45:43
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2003-07-16 17:00:32
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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
2004-04-20 09:48:22
http://php5.kiev.ua/manual/ru/function.trim.html
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);
?>

:)
2004-05-26 17:50:27
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2004-11-12 09:44:52
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Another way to trim all the elements of an array
<?php
$newarray 
array_map('trim'$array);
?>
2005-02-07 18:46:46
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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.
2005-03-04 12:25:24
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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.
2005-03-29 14:49:56
http://php5.kiev.ua/manual/ru/function.trim.html
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;
}
2005-03-30 22:37:22
http://php5.kiev.ua/manual/ru/function.trim.html
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!';
}

?>
2005-05-17 15:47:45
http://php5.kiev.ua/manual/ru/function.trim.html
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_fp1024);
          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_fpsubstr($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;
  }

?>
2005-06-05 07:01:57
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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";
}
2005-06-15 00:54:12
http://php5.kiev.ua/manual/ru/function.trim.html
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 :)
2005-07-05 13:20:57
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2005-07-16 03:49:29
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2005-09-01 14:30:57
http://php5.kiev.ua/manual/ru/function.trim.html
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 :-)
2005-12-07 14:28:40
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
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.
2005-12-14 16:10:42
http://php5.kiev.ua/manual/ru/function.trim.html
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.
2006-01-17 11:30:58
http://php5.kiev.ua/manual/ru/function.trim.html
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
2006-02-18 15:03:49
http://php5.kiev.ua/manual/ru/function.trim.html
I had some issues using <? array_map('trim',$array?> when there was an array in array.  All arrays were replaced by the string "Array", drove me crazy.
Hopefully this will help someone:
<?php
function trim_array($totrim) {
    if (
is_array($totrim)) {
       
$totrim array_map("trim_array"$totrim);
    } else {
       
$totrim trim($totrim);
    }
    return 
$totrim;
}
?>
USE:
<?php
$trimmed_array 
trim_array($untrimmed_array);
?>

This function should recurse all embeded arrays.
2006-07-10 07:39:59
http://php5.kiev.ua/manual/ru/function.trim.html
If you need to trim a string from the beginning and end of a string, then this function maybe prove handy.

<?php
function lrclean($str,$rm) {
 
$i strlen($rm);
  do {
    if (
substr($str,0,$i) == $rm) {$str substr($str,$i);}
  } while (
substr($str,0,$i) == $rm);

  do {
    if (
substr($str,-$i,$i) == $rm) {$str substr($str,0,-$i);}
  } while (
substr($str,-$i,$i) == $rm);
 
  return 
$str;
}

// prints 'text'
echo lrclean('xyztextxyz','xyz');
?>
2006-11-19 14:40:35
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
2007-01-12 08:06:01
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
I use this to remove leading, trailing and "more than one" space in between words.

$pat[0] = "/^\s+/";
$pat[1] = "/\s{2,}/";
$pat[2] = "/\s+\$/";
$rep[0] = "";
$rep[1] = " ";
$rep[2] = "";
$str = "  Words with   lots      of  spaces     ";
$str = preg_replace($pat,$rep,$str);
// Output
"Words with lots of spaces"
2007-01-24 10:04:11
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
trim's code can of course be simplified with some use of the trim() function....

<?php
$str 
"  Words with  lots      of  spaces    ";
$str preg_replace('/\s\s+/'' 'trim($str));
?>

Doing the trim() first reduces the workload being put on the more expensive preg_replace().
2007-03-19 16:36:00
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Here's a faster way to do what's described below:

<?php
$string 
'This string  has   no    whitespaces.';
echo 
ereg_replace' +'''$string );
?>

Output: Thisstringhasnowhitespaces.

If you want it to replace only single whitespaces instead of both single and cascading dito, remove the + in the first parameter of ereg_replace().
2007-06-26 20:13:08
http://php5.kiev.ua/manual/ru/function.trim.html
Responding to Robin Leffmann:
jayoungh5 wrote a function to trim whitespace on the left, on the right, in the middle, everywhere (Below). It iterates through the string's characters. Yours, claimed to be faster, uses a regex function. I think it should be slower since I believe that dealing with a regex is iterative in nature and add to that the possibility of recursion! Perhaps your function is shorter in code lines.
I am not absolutely positive, so take this as a clue but research for a more solid truth.
2007-07-06 03:48:33
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Robin Leffman's code could be improved further...
<?php
$string 
'This string  has   no    whitespaces.';
echo 
str_replace(' '''$string );
?>

Of course, like Leffman's code, that only removes space characters, not necessarily all whitespace (or characters in some arbitrary $whiteSpace string). For that
<?php
function trimlrm ($hayStack$whiteSpaceChars)
{
   
$char $whiteSpaceChars[0];
   
$chars str_repeat($charstrlen($whiteSpaceChars);
   
$trimmed strtr($hayStack$whiteSpaceChars$chars)));
    return 
str_replace($char''$trimmed);
}
?>
would probably work, but like the others, fails to give '..' the same specialness that it has in trim().
2007-08-10 01:49:59
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
masteremployment's solution in a function, and with preg_replace() instead of ereg_replace():

<?php
function removeWhitespace($string)
{
    if (!
is_string($string))
        return 
false;

   
$string preg_quote($string'|');
    return 
preg_replace('|  +|'' '$string);
}
?>
2007-08-16 08:26:01
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
I have made this simple function to trim the whole string instead of just the beginning and end...

<?php

function strTrimTotal($input) {

   
$input trim($input);

    for(
$i=0;$i<strlen($input);$i++) {

        if(
substr($input$i1) != " ") {

           
$output .= trim(substr($input$i1));

        } else {

           
$output .= " ";

        }

    }

    return 
$output;
}

?>
2007-08-24 06:03:29
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
As already commented by thers the solution from Robin Leffmann to remove "all" 
the spaces from a string not only does not trim the "other" chars besides plain
spaces but is at all not faster than jayoungh5's proposal.

The only faster way I can imagine of is:

function trimall($str, $charlist = " \t\n\r\0\x0B")
{
  return str_replace(str_split($charlist), '', $str);
}

However jayoungh5's one might still be faster for very large sets of characters
to be stripped.
2007-09-01 15:08:30
http://php5.kiev.ua/manual/ru/function.trim.html
as mentioned, a str_replace(' ', '', $string) does execute faster than Robin Leffmann's ereg_replace; however, the regular expression Leffmann supplied has the ability of also stripping out only -single- whitespaces as by his comment, whereas the blunt str_replace will simply sweep all of them away, single as cascading. one tool for each job.
2007-12-24 11:53:23
http://php5.kiev.ua/manual/ru/function.trim.html
admin at semaster dot ru's array_trim function is flawed in that it will change the type of nulls and numeric variables (to strings).

Here is a better version, although it lacks charlist support:

<?php
function array_trim($var) {
    if (
is_array($var))
        return 
array_map("array_trim"$var);
    if (
is_string($var))
        return 
trim($var);
    return 
$var;
}
?>

-Rob
2008-04-16 19:50:35
http://php5.kiev.ua/manual/ru/function.trim.html
I've noticed that many needs to remove multiple lines in the end of a string, so I made this function. Pretty easy, actually. It removes all unnecessary newlines (or something else, if $char is set)

<?php
function remove_unnecessary ($str$char "\n") {
    while (
true) {
        if (
substr ($str, -(strlen($char))) == $char) {
           
$str substr ($str0, -(strlen($char)));
        } else {
            break;
        }
    }
   
    return 
$str;
}

$Str "Hello\nHello\n\n\n\n\n\n\n\n\n";

// Outputs: Hello\nHello
echo remove_unnecessary ($Str);
?>
2008-04-25 13:19:25
http://php5.kiev.ua/manual/ru/function.trim.html
Yet another array trim, recursive too.
I think this one is pretty usefull, though it lacks charlist, you can add that functionality if you need to, it's not that hard ;)
Anyway, one feature that I added, and I find pretty usefull, is that it can splice an empty position if you want to

<?php
function array_trim_recursive(&$array$splice_empty true) {
    foreach(
$array as $k => &$v) {
        if(
is_array($v)) {
           
array_trim_recursive($v$splice_empty);
        } else {
           
$array[$k] = trim($v);
           
iif(!$v && $splice_empty) {
               
array_splice($array$k1);
            }
        }
    }
}
?>
2008-04-26 01:17:23
http://php5.kiev.ua/manual/ru/function.trim.html
If you want to remove all excessive spaces and leave just a single one, like the way HTML text gets rendered in the browser, this function (modified from one posted here earlier) will work:

function str_squeeze($test) {
    return trim(ereg_replace( ' +', ' ', $test));
}

The result is that a string such as "hello___how_are__you_" (where the _ is a space) will result in a more sane "hello_how_are_you".
2008-06-18 02:42:56
http://php5.kiev.ua/manual/ru/function.trim.html
The following function will assist you in case you wish to trim a string but keep the parts trimmed. I'm using it to strip phrases for translation on my site.

Example:
cleanPhrase('  (this () is it)');

Will return:
Array
(
    [left] =>   ( 
    [right] => ) 
    [clean] => this () is it
)

<?php
   
/**
     * Trims some of the characters from the phrase
     *
     * @param string $phrase - to be "cleaned"
     * @param string $dirtyChars - the characters that need be removed
     * @return string
     */
   
public static function cleanPhrase($phrase$dirtyChars " \t\n()[]:.\"'") {
       
$len strlen($phrase);
        for(
$i=0$i $len$i++) {
           
$pos strpos($dirtyCharssubstr($phrase$i1)); 
            if (
$pos === false) break;
        }
        for(
$j=$len-1$j >= 0$j--) {
           
$pos strpos($dirtyCharssubstr($phrase$j1)); 
            if (
$pos === false) break;
        }
       
       
$res = array();
       
$res['left'] = substr($phrase0$i);
       
$res['right'] = substr($phrase$j+1);
       
$res['clean'] = substr($phrase$i$j-$i+1);
       
        return 
$res;
    }
?>
2008-08-26 09:21:41
http://php5.kiev.ua/manual/ru/function.trim.html
A simple function to clear extra white spaces along a string.
<?php
function TrimStr($str)
{
   
$str trim($str);
    for(
$i=0;$i strlen($str);$i++)
    {

        if(
substr($str$i1) != " ")
        {

           
$ret_str .= trim(substr($str$i1));

        }
        else
        {
            while(
substr($str,$i,1) == " ")
           
            {
               
$i++;
            }
           
$ret_str.= " ";
           
$i--; // ***
       
}
    }
    return 
$ret_str;
}
?>

[EDIT BY danbrown AT php DOT net: Contains a fix provided by (info AT deep-soft DOT com) to address the issue where "it deletes the first char after spaces (because of while)."]
2008-11-21 19:50:57
http://php5.kiev.ua/manual/ru/function.trim.html
some of "trim array" functions
this trim strings, arrays and objects:
<?php
function trimA($str$set=null)
{
    if(
is_Array($str) || is_Object($str))
        foreach(
$str as &$s)
           
$s=trimA($s,$set);
    elseif(
$set===null)$str=trim($str);
    else 
$str=trim($str,$set);
    return 
$str;
}
?>
2009-01-27 05:29:03
http://php5.kiev.ua/manual/ru/function.trim.html
If what you need is delete a string instead of character, this function could help you:

<?php
function trimString($input$string){
       
$input trim($input);
       
$startPattern "/^($string)+/i";
       
$endPattern "/($string)+$/i";
        return 
trim(preg_replace($endPattern''preg_replace($startPattern,'',$input)));
}
?>

Use:
<?php
echo trimString("      Hello world!. I said hello""hello")
?>
Will return:
world!. I said
2009-02-26 08:23:47
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
small fix for the trimString function to proof against slash and backslash:

<?php
function trimString($input$string){
       
$input trim($input);
       
$string str_replace("\\""\\\\"$string);
       
$string str_replace('/''\\/'$string);
       
$startPattern "/^($string)+/i";
       
$endPattern "/($string)+$/i";
        return 
trim(preg_replace($endPattern''preg_replace($startPattern,'',$input)));
}
?>
2009-03-21 05:48:41
http://php5.kiev.ua/manual/ru/function.trim.html
I made this function to trim texts.
Removes al double horizontal and vertical whitespace chars.

<?php
function trimText($str)
{
   
$str trim($str);
   
$str preg_replace('/\h+/'' '$str);
   
$str preg_replace('/\v{3,}/'PHP_EOL.PHP_EOL$str);

    return 
$str;
}
?>
2009-04-08 16:35:38
http://php5.kiev.ua/manual/ru/function.trim.html
A cell read from an Excel sheet appeared to have a whitespace, and this was not getting trimmed. By converting to hex, it seems the char was a hard return.

Successfully trimmed it by:

<?php
trim
($value"\xc2\xa0");
?>

The actual hex values may vary by character set, check with bin2hex() for what's actually there.
2009-04-21 06:37:49
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
It should be mentioned that if you use the second charlist parameter, you are overriding the defaults, not adding to them. You would need to either explicitly add them to the charlist or call trim twice, like so:

<?php

$str 
trim(trim($str), './@#$');

?>
2009-05-15 12:01:44
http://php5.kiev.ua/manual/ru/function.trim.html
Note for trimming arrays that you can easily use array_map if you don't want to specify the characters.

<?php
var_dump
(array_map('trim', Array(' Test ''Test '' Test')));
?>
2009-05-22 15:39:31
http://php5.kiev.ua/manual/ru/function.trim.html
As another poster has pointed out, chr(160) is also important to filter out. This is the ascii representation of an html "hard space", and it will show up sometimes in your datasources, especially if the data was copied-and-pasted from a web browser from a page that used hard spaces to force layout.

This is not just a Windows problem. I am on a Mac and I have had to deal with it too (although the data in question may have indeed originally come from a windows user, I don't know.)
2009-08-06 12:54:00
http://php5.kiev.ua/manual/ru/function.trim.html
Admendum to this note:
<?php
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean trim($binary"\x00..\x1F");
?>
I had a big time with my WWW parser, which produced XML errors because of illegal characters in the outside files. So I decided to wipe them out.
If you want to remove all illegal SGML characters (ASCII coces 0 to 31 inclusive and 127 to 159 inclusive) from the whole string, (remember that trim doesn't work inside a string, just on the borders) here's how to do that:

<?php
$title 
"Autobus zamiast \x1EHetmana\x1D";
$replaceArray = array(array(), array()); // this is a replace array for illegal SGML characters;
for ($i=0$i<32$i++)                  // produces a correct XML output
{
   
$replaceArray[0][] = chr($i);
   
$replaceArray[1][] = "";
}
for (
$i=127$i<160$i++)
{
   
$replaceArray[0][] = chr($i);
   
$replaceArray[1][] = "";
}
$title str_replace($replaceArray[0], $replaceArray[1], $title); // get rid of illegal SGML chars
echo $title// prints out "Autobus zamiast Hetmana"
?>

Now $title can be printed into an XML/XHTML file without worries.
2009-09-09 18:59:02
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
There is a trap when making "form prefilters". Something like
$_POST = array_map('trim', $_POST)
may be not what we wanted, because when there are arrays in form made by field[] this "prefilter" return not an array but, according to his behavior, string. So as a effect we see in var_dump not array but field = "Array" what can mess up our validation.
2010-02-17 04:36:20
http://php5.kiev.ua/manual/ru/function.trim.html
Trims occurances of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what$words$char_list '') {
    if(!
is_array($words)) return false;
   
$char_list .= " \t\n\r\0\x0B"// default trim chars
   
$pattern "(".implode("|"array_map('preg_quote'$words)).")\b";
   
$str trim(preg_replace('~'.$pattern.'$~i'''preg_replace('~^'.$pattern.'~i'''trim($what$char_list))), $char_list);
    return 
$str;
}

// for example:
$trim_list = array('AND''OR');

$what ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what$trim_list)); // => "x = 1 AND b = 2"

$what ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what$trim_list',')); // => "ORDER BY x DESC, b ASC"
?>
2010-04-09 07:29:39
http://php5.kiev.ua/manual/ru/function.trim.html
While inserting data from web forms to databases, trimming the posted values to remove the spaces from the left and right sides can be a good idea to avoid the user faults. This code have to be located before the DB operations.

<?php 

/* Stripping whitespaces from left and right sides of all posted data.
 * Put this before working with posted data.
 *
*/

// Remove whitespaces from left and right sides.
function removeSpaces($str) {
 
$newStr trim($str);
  return 
$newStr;
}

// If any data posted to the page, send them for trimming.
if ($_POST) {
  foreach (
$_POST as $var => $value) {
   
$value=removeSpaces($value);
   
$_POST[$var] = $value;
  }
}

?>
2010-05-16 10:45:27
http://php5.kiev.ua/manual/ru/function.trim.html
Non-breaking spaces can be troublesome with trim:

<?php
// turn some HTML with non-breaking spaces into a "normal" string
$myHTML "&nbsp;abc";
$converted strtr($myHTMLarray_flip(get_html_translation_table(HTML_ENTITIESENT_QUOTES)));

// this WILL NOT work as expected
// $converted will still appear as " abc" in view source
// (but not in od -x)
$converted trim($converted);

// &nbsp; are translated to 0xA0, so use:
$converted trim($converted"\xA0"); // <- THIS DOES NOT WORK

// EDITED>>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted trim($converted,chr(0xC2).chr(0xA0)); // should work

// PS: Thanks to John for saving my sanity!
?>
2010-07-09 05:28:06
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Please consider the following:

<?php
$a 
'0';

if (
trim($a)) {
  echo 
'Never ever ...';
} else {
  echo 
'YES, "(bool)trim(\'0\')" is FALSE';
}
?>

So never forget to use:

if (trim($a) != '') ...

This cast costs me some time...
2010-08-25 08:59:25
http://php5.kiev.ua/manual/ru/function.trim.html
To trim all strings and remove CR.

<?php
$arr 
= array('apple''orange');
$arr2 = array('name' => 'James''zipcode' => '1234'$arr);
$data = array($arr2'peach');

array_walk_recursive($data'trim_all');
print_r($data);

function 
trim_all(&$value)

  if (
is_array($value))
  {   
   
array_walk_recursive($value'trim_all');
  }
  else
  {   
   
$value trim(str_replace("\r\n""\n"$value));
  }
}
?>
2010-10-01 05:11:34
http://php5.kiev.ua/manual/ru/function.trim.html
Here's a function to trim strings recursively within an array.

<?php

// Trim a string or an array of strings recursively
function trim_r($array) {
    if (
is_string($array)) {
        return 
trim($array);
    } else if (!
is_array($array)) {
        return 
'';
    }
   
$keys array_keys($array);
    for (
$i=0$i<count($keys); $i++) {
       
$key $keys[$i];
        if ( 
is_array($array[$key]) ) {
           
$array[$key] = trim_r($array[$key]);
        } else if ( 
is_string($array[$key]) ) {
           
$array[$key] = trim($array[$key]);
        }
    }
    return 
$array;
}

// Test
$a = array(' cat '' dog ' => ' mouse '234);
print_r(trim_r($a));

?>

Array
(
    [0] => cat
    [ dog ] => mouse
    [1] => 234
)
2011-04-05 09:49:13
http://php5.kiev.ua/manual/ru/function.trim.html
On my application I had several users submit what to me appeared as "empty strings", whereas in fact they were submitting the &shy; character.

Trim, by default, does not strip this character (Though arguably it should). The following code strips this character from your input:

<?php

// As the &shy; character is invisible we'll simply use the ASCII numeric representation, and decode via chr():
$string trim($stringchr(173));

// If you wish to strip all occurences this will work:
$string str_replace(chr(173), ""$string);

?>

Gerard
2011-06-03 11:38:37
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Combined filter and trim array.

<?php
function _trim_value(&$value) {
    if (
is_string($value))
       
$value trim($value);
}

function 
array_filter_and_trim($arr) {
   
array_walk($arr'_trim_value');
    return 
array_filter($arr);
}
?>
2011-08-10 08:22:56
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
trim_chars
(trim string or character off beginning and end of a string)

<?php
function  trim_chars($string,$char,$whitespace_first=null){
   
$string = ($whitespace_first trim($string) : $string);
   
$trimmed = ( substr($string,-1)==$char substr($string,($string[0]==$char 0),-1) : substr($string,($string[0]==$char 0)) );
    return ( 
$trimmed == $string $trimmed trim_str($trimmed,$char) );
}
?>

usage:
<?php
 
echo trim_chars('&%$abc&%$''&%$'); 
  echo 
trim_chars(' &%$abc&%$ ''&%$'true); 
  echo 
trim_chars(' %%%abc%%% ''&%$'false); 
  echo 
trim_chars('&%$abc&%$ ''&%$'false); 
?>

outputs:
  'abc'
  'abc'
  ' &%$abc&%$ '
  'abc&%$ '
2011-11-07 20:37:56
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
If you want to trim html whitespace (&nbsp; entities and <br /> tags) you can use this function. Input should be valid utf8.

<?php

 
function htmltrim($string)
  {
   
$pattern '(?:[ \t\n\r\x0B\x00\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}]|&nbsp;|<br\s*\/?>)+';
    return 
preg_replace('/^' $pattern '|' $pattern '$/u'''$string);
  }

?>
2012-02-06 16:20:22
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Here is a way to eliminate all the intermediate whitespaces in a string, but leaving just one whitespace in order to keep data such as names in a correct order.

example:
<?php
$text 
"john      doe      doe";

//here is the function
   
while(substr_count($text,"  ") != 0){
       
$text str_replace("  "," ",$text);
    }

//The result would be: john doe doe

?>
2012-02-23 18:30:30
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
Alternate way to trim and combine duplicate whitespace characters in a string:
<?php
      $text 
"   john      q.      doe   ";
     
$text trim(implode(' 'preg_split('/\s+/'$text)));
?>
2012-03-08 19:50:16
http://php5.kiev.ua/manual/ru/function.trim.html
Автор:
I needed a quick function to check if a string was "trimmable".
Maybe some of you could need this:

function trim_check($str){
    if(strlen($str) > strlen(trim($str))) return true;
    else return false;
}
2012-04-03 13:23:35
http://php5.kiev.ua/manual/ru/function.trim.html

    Поддержать сайт на родительском проекте КГБ