It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
(PHP 4, PHP 5, PHP 7)
trim — Dizgenin başındaki ve sonundaki boşlukları (veya diğer karakterleri) budar
$dizge
[, string $karakterler
] )
Bu işlev dizge'nin başındaki ve sonundaki
boşlukları budar. İkinci değiştirge olmaksızın trim()
sadece aşağıdaki karakterleri budayacaktır:
dizgeBudanacak dizge.
karakterler
Seçimlik olarak, karakterler değiştirgesi
kullanılarak budanacak karakterler belirlenebilir.
Basitçe budamak istediğiniz tüm karakterleri belirtin. Bir karakter
aralığını .. kullanarak belirtebilirsiniz.
Budanmış dizge.
| Sürüm: | Açıklama |
|---|---|
| 4.1.0 |
İsteğe bağlı karakterler değiştirgesi eklendi.
|
Örnek 1 - trim() işlevinin kullanımı
<?php
$metin = "\t\tBir kaç kelam :) ... ";
$ikil = "\x09Örnek dizge\x0A";
$selam = "Merhaba Dünya";
var_dump($metin, $ikil, $selam);
print "\n";
$kırpık = trim($metin);
var_dump($kırpık);
$kırpık = trim($metin, " \t.");
var_dump($kırpık);
$kırpık = trim($selam, "aerMy");
var_dump($kırpık);
// $ikil'in başındaki ve sonundaki ASCII denetim karakterlerini budar
// (0'dan 31'e kadar, 0 ve 31 dahil)
$temiz = trim($ikil, "\x00..\x1F");
var_dump($temiz);
?>
Yukarıdaki örneğin çıktısı:
string(25) " Bir kaç kelam :) ... " string(14) " Örnek dizge " string(14) "Merhaba Dünya" string(21) "Bir kaç kelam :) ..." string(17) "Bir kaç kelam :)" string(9) "haba Dün" string(12) "Örnek dizge"
Örnek 2 - trim() işlevini dizi değerlerine uygulama
<?php
function değeri_buda(&$değer)
{
$değer = trim($değer);
}
$meyve = array('elma','muz ', ' muşmula ');
var_dump($meyve);
array_walk($meyve, 'değeri_buda');
var_dump($meyve);
?>
Yukarıdaki örneğin çıktısı:
array(3) {
[0]=>
string(4) "elma"
[1]=>
string(4) "muz "
[2]=>
string(10) " muşmula "
}
array(3) {
[0]=>
string(4) "elma"
[1]=>
string(3) "muz"
[2]=>
string(8) "muşmula"
}
It may be useful to know that trim() returns an empty string when the argument is an unset/null variable.
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!
?>
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 full width space will return mess character, when target string starts with '《'
@example
echo trim("《", " ");
@return
�
php version 5.4.27
[EDIT by cmb AT php DOT net: it is not necessarily safe to use trim with multibyte character encodings. The given example is equivalent to echo trim("\xe3\80\8a", "\xe3\x80\x80").]
Another way to trim all the elements of an array
<?php
$newarray = array_map('trim', $array);
?>
This function trims regular expressions from strings.
<?php
function preg_trim( $string, $pattern ) {
$pattern = array( "/^" . $pattern . "*/", "/" . $pattern . "*$/" );
return preg_replace( $pattern, "", $string );
}
?>
The following example outputs "Hello, world":
<?php
$hello = " ...%20Hello, world!";
echo preg_trim( $hello, "[^a-zA-Z]" );
?>
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"
?>
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!';
}
?>
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");
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
Trim will generate a warning is you try to trim an empty string if this is a problem for you can test with is_string