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
trim
(PHP 4, PHP 5)
trim — Entfernt Whitespaces (oder andere Zeichen) am Anfang und Ende eines Strings
Beschreibung
$str
[, string $charlist
] )
Die Funktion entfernt Whitespaces an Anfang und Ende von
str und gibt den String dann zurück.
Ohne Verwendung des zweiten Parameters entfernt trim()
folgende Zeichen:
- " " (ASCII 32 (0x20)), ein normales Leerzeichen.
- "\t" (ASCII 9 (0x09)), ein Tabulatorzeichen.
- "\n" (ASCII 10 (0x0A)), einen Zeilenvorschub (Line Feed).
- "\r" (ASCII 13 (0x0D)), ein Wagenrücklaufzeichen (Carriage Return).
- "\0" (ASCII 0 (0x00)), das NUL-Byte.
- "\x0B" (ASCII 11 (0x0B)), ein vertikaler Tabulator.
Parameter-Liste
-
str -
string erwartet die zu trimmende Zeichenkette.
-
charlist -
Optional kann die Liste der Zeichen angegeben werden, die an Anfang und Ende der Zeichenkette entfernt werden sollen. Um diese Zeichen anzugeben, wird der
charlistParameter verwendet. Er enthält eine Liste aller zu entfernenden Zeichen. Mit .. können darüber hinaus auch ganze Bereiche von Zeichen angegeben werden.
Rückgabewerte
Der gekürzte String.
Changelog
| Version | Beschreibung |
|---|---|
| 4.1.0 |
Einführung des optionalen charlist Parameters.
|
Beispiele
Beispiel #1 Beispiel zur Verwendung von trim()
<?php
$text = "\t\tDieser Text besteht aus mehreren Wörtern :) ... ";
$binary = "\x09Beispeilhafter String\x0A";
$hello = "Hallo Welt";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " \t.");
var_dump($trimmed);
$trimmed = trim($hello, "Htla");
var_dump($trimmed);
$trimmed = trim($hello, 'HtWr');
var_dump($trimmed);
// Trimmen der ASCII Steuerzeichen an Anfang und Ende von $binary
// (inklusive der Zeichen von ASCII 0 bis 31)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
string(51) " Dieser Text besteht aus mehreren Wörtern :) ... " string(23) " Beispeilhafter String " string(10) "Hallo Welt" string(47) "Dieser Text besteht aus mehreren Wörtern :) ..." string(43) "Dieser Text besteht aus mehreren Wörtern :)" string(4) "o We" string(8) "allo Wel" string(21) "Beispeilhafter String"
Beispiel #2 Trimmen von Array-Werten mittels trim()
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruechte = array('Apfel','Banane ', ' Preiselbeere ');
var_dump($fruechte);
array_walk($fruechte, 'trim_value');
var_dump($fruechte);
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
array(3) {
[0]=>
string(5) "Apfel"
[1]=>
string(7) "Banane "
[2]=>
string(11) " Preiselbeere "
}
array(3) {
[0]=>
string(5) "Apfel"
[1]=>
string(6) "Banane"
[2]=>
string(9) "Preiselbeere"
}
Anmerkungen
Hinweis: Mögliche Überraschungen: Entfernung mittlerer Zeichen
Weil trim() Zeichen vom Anfang und Ende einer Zeichenkette (string) entfernt, kann es verwirrend sein, wenn Zeichen aus der Mitte gelöscht (oder nicht) werden. trim('abc', 'bad') entfernt 'a' und 'b', weil es 'a' entfernt, verschiebt daher 'b' an den Anfang um ebenfalls entfernt zu werden. Daher "funktioniert" es, trim('abc', 'b') dagegen scheinbar nicht.
Siehe auch
- ltrim() - Entfernt Leerraum (oder andere Zeichen) vom Anfang eines Strings
- rtrim() - Entfernt Leerraum (oder andere Zeichen) vom Ende eines Strings
- str_replace() - Ersetzt alle Vorkommen des Suchstrings durch einen anderen String
Non-breaking spaces can be troublesome with trim:
<?php
// 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"); // <- 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!
?>
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
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");
I think this is my implementation of trim...
<?php
/*
* Function: "trim"
* @str = source
* @charlist = list of characters to be trimmed from the source
*
* Author: syn-attack@devilzc0de.org
* Full documentation in http://php.net/manual/en/function.trim.php
*/
function __trim($str, $charlist = '') {
$result = '';
/* list of forbidden chars to be trimmed */
$forbidden_list = array(" ", "\t", "\r", "\n", "\0", "\x0B");
if (empty($charlist)) {
for ($i = 0; $i < strlen($str); $i++) {
if (($str[$i] != $forbidden_list[0]) &&
($str[$i] != $forbidden_list[1]) &&
($str[$i] != $forbidden_list[2]) &&
($str[$i] != $forbidden_list[3]) &&
($str[$i] != $forbidden_list[4]) &&
($str[$i] != $forbidden_list[5])) {
$result .= $str[$i];
}
}
}
else if (!empty($charlist)) {
$is_not_same = true;
for ($i = 0; $i < strlen($str); $i++) {
for ($j = 0; $j < strlen($charlist); $j++) {
if ($str[$i] != $charlist[$j]) {
$is_not_same = true;
}
else if ($str[$i] == $charlist[$j]) {
$is_not_same = false;
break;
}
}
if ($is_not_same == true) {
$result .= $str[$i];
}
}
}
return ($result);
}
$str = "Paulus Gandung Prakosa";
echo __trim($str);
?>
To show off the empty positions in a string by means of trim():
<?php
$string = " Hello World! ";
echo $string;
echo " Has : ".strlen($string)." letter(s). One by one according to the following:<br />";
echo "<br />".$rightt = strlen(ltrim($string)) - strlen(trim($string))." empty position(s) from right.";
echo "<br />".$leftt = strlen(rtrim($string)) - strlen(trim($string))." empty position(s) from left.<br />";
$length = strlen($string);
for($x = 0; $x < $length; $x++){
$letter = substr($string, $x, 1);
if($letter <> " ")
echo "<br />Position $x ===> ".substr($string, $x, 1);
else
echo "<br />Position $x ===> Empty";
}
?>
the output is:
Hello World! Has : 19 letter(s). One by one according to the following:
3 empty position(s) from right.
4 empty position(s) from left.
Position 0 ===> Empty
Position 1 ===> Empty
Position 2 ===> Empty
Position 3 ===> Empty
Position 4 ===> H
Position 5 ===> e
Position 6 ===> l
Position 7 ===> l
Position 8 ===> o
Position 9 ===> Empty
Position 10 ===> W
Position 11 ===> o
Position 12 ===> r
Position 13 ===> l
Position 14 ===> d
Position 15 ===> !
Position 16 ===> Empty
Position 17 ===> Empty
Position 18 ===> Empty
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, $i, 1) != " ")
{
$ret_str .= trim(substr($str, $i, 1));
}
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)."]
If you want to check whether something ONLY has whitespaces, use the following:
<?php
if (trim($foobar)=='') {
echo 'The string $foobar only contains whitespace!';
}
?>
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
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"
?>
On my application I had several users submit what to me appeared as "empty strings", whereas in fact they were submitting the ­ 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 ­ character is invisible we'll simply use the ASCII numeric representation, and decode via chr():
$string = trim($string, chr(173));
// If you wish to strip all occurences this will work:
$string = str_replace(chr(173), "", $string);
?>
Gerard
When you choose characters to trim, the defaults are replaced by those, so if you wish to trim the defaults in addition to some extras, you need to specify the defaults every time. Here is a little helper function that will trim the defaults, plus your additions:
<?php
function trim_plus($str, $chars = '') {
return trim($str, " \t\n\r\0\x0B$chars");
}
var_dump(trim(' a- ', '-')); # no changes
var_dump(trim(' a- ', '- ')); # works
var_dump(trim_plus(' a- ', '-')); # works
?>
