Удалить все пробелы из текста можно двумя функциями str_replace() и preg_replace() или ereg_replace() . Первая менее эффективна, т.к. табы и переносы строк просто так не удалятся.
Например
Есть текст рыба в котором нужно удалить все пробелы.
Получается, что preg_replace эффективней удалит пробелы, но может переносы случится так что удалять табы и переносы и не нужно.
(PHP 4, PHP 5, PHP 7)
trim — Удаляет пробелы (или другие символы) из начала и конца строки
Описание
Список параметров
Можно также задать список символов для удаления с помощью необязательного аргумента character_mask . Просто перечислите все символы, которые вы хотите удалить. Можно указать конструкцию .. для обозначения диапазона символов.
Возвращаемые значения
Примеры
Пример #1 Пример использования trim()
= " These are a few words 🙂 . " ;
$binary = "x09Example stringx0A" ;
$hello = "Hello World" ;
var_dump ( $text , $binary , $hello );
$trimmed = trim ( $text );
var_dump ( $trimmed );
$trimmed = trim ( $text , " ." );
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 );
Результат выполнения данного примера:
Пример #2 Обрезание значений массива с помощью trim()
$fruit = array( ‘apple’ , ‘banana ‘ , ‘ cranberry ‘ );
var_dump ( $fruit );
array_walk ( $fruit , ‘trim_value’ );
var_dump ( $fruit );
Результат выполнения данного примера:
Примечания
Замечание: Возможные трюки: удаление символов из середины строки
Так как trim() удаляет символы с начала и конца строки string , то удаление (или неудаление) символов из середины строки может ввести в недоумение. trim(‘abc’, ‘bad’) удалит как ‘a’, так и ‘b’, потому что удаление ‘a’ сдвинет ‘b’ к началу строки, что также позволит ее удалить. Вот почему это "работает", тогда как trim(‘abc’, ‘b’) очевидно нет.
Смотрите также
- ltrim() – Удаляет пробелы (или другие символы) из начала строки
- rtrim() – Удаляет пробелы (или другие символы) из конца строки
- str_replace() – Заменяет все вхождения строки поиска на строку замены
User Contributed Notes 16 notes
When specifying the character mask,
make sure that you use double quotes
= "
Hello World " ; //here is a string with some trailing and leading whitespace
$trimmed_correct = trim ( $hello , "
" ); // $trimmed_incorrect = trim ( $hello , ‘
‘ ); // print( "—————————-" );
print( "TRIMMED OK:" . PHP_EOL );
print_r ( $trimmed_correct . PHP_EOL );
print( "—————————-" );
print( "TRIMMING NOT OK:" . PHP_EOL );
print_r ( $trimmed_incorrect . PHP_EOL );
print( "—————————-" . PHP_EOL );
?>
Here is the output:
Non-breaking spaces can be troublesome with trim:
// 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" ); // >
// 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!
?>
trim is the fastest way to remove first and last char.
Benchmark comparsion 4 different ways to trim string with ‘/’
4 functions with the same result – array exploded by ‘/’
print cycle ( "str_preg(‘ $s ‘);" , $times );
print cycle ( "str_preg2(‘ $s ‘);" , $times );
print cycle ( "str_sub_replace(‘ $s ‘);" , $times );
print cycle ( "str_trim(‘ $s ‘);" , $times );
print cycle ( "str_clear(‘ $s ‘);" , $times );
function cycle ( $function , $times ) <
$count = 0 ;
if( $times 1 ) <
return false ;
>
$start = microtime ( true );
while( $times > $count ) <
eval( $function );
$count ++;
>
$end = microtime ( true ) – $start ;
return "
$function exec time: $end " ;
>
function str_clear ( $s ) <
$s = explode ( ‘/’ , $s );
$s = array_filter ( $s , function ( $s ));
return $s ;
>
function str_preg2 ( $s ) <
$s = preg_replace ( ‘/((? , ” , $s );
$s = explode ( ‘/’ , $s );
return $s ;
>
function str_preg ( $s ) <
$s = preg_replace ( ‘/^(/?)(.*?)(/?)$/i’ , ‘$2’ , $s );
$s = explode ( ‘/’ , $s );
return $s ;
>
function str_sub_replace ( $s ) <
$s = str_replace ( ‘/’ , ” , mb_substr ( $s , 0 , 1 )) . mb_substr ( $s , 1 , – 1 ) . str_replace ( ‘/’ , ” , mb_substr ( $s , – 1 ));
$s = explode ( ‘/’ , $s );
return $s ;
>
function str_trim ( $s ) <
$s = trim ( $s , ‘/’ );
$s = explode ( ‘/’ , $s );
return $s ;
>
To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:
It is worth mentioning that trim, ltrim and rtrim are NOT multi-byte safe, meaning that trying to remove an utf-8 encoded non-breaking space for instance will result in the destruction of utf-8 characters than contain parts of the utf-8 encoded non-breaking space, for instance:
non breaking-space is "u
$input = "u
$output = trim($input, "u
$output got both "u
if you are using trim and you still can’t remove the whitespace then check if your closing tag inside the html document is NOT at the next line.
there should be no spaces at the beginning and end of your echo statement, else trim will not work as expected.
Trim full width space will return mess character, when target string starts with ‘《’
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("xe3808a", "xe3x80x80").]
Standard trim() functions can be a problematic when come HTML entities. That’s why i wrote "Super Trim" function what is used to handle with this problem and also you can choose is trimming from the begin, end or booth side of string.
function strim ( $str , $charlist = " " , $option = 0 ) <
if( is_string ( $str ))
<
// Translate HTML entities
$return = strtr ( $str , array_flip ( get_html_translation_table ( HTML_ENTITIES , ENT_QUOTES )));
// Remove multi whitespace
$return = preg_replace ( "@s+s@Ui" , " " , $return );
// Choose trim option
switch( $option )
<
// Strip whitespace (and other characters) from the begin and end of string
default:
case 0 :
$return = trim ( $return , $charlist );
break;
// Strip whitespace (and other characters) from the begin of string
case 1 :
$return = ltrim ( $return , $charlist );
break;
// Strip whitespace (and other characters) from the end of string
case 2 :
$return = rtrim ( $return , $charlist );
break;
Beware with trimming apparently innocent characters. It is NOT a Unicode-safe function:
echo trim ( ‘≈ [Approximation sign]’ , ‘– [en-dash]’ ); // �� [Approximation sig
?>
The en-dash here is breaking the Unicode characters.
And also prevents the open-square-bracket from being seen as part of the characters to trim on the left side, letting it untouched in the resulting string.
If you want to check whether something ONLY has whitespaces, use the following:
if ( trim ( $foobar )== ” ) <
echo ‘The string $foobar only contains whitespace!’ ;
>
Simple Example I hope you will understand easily:
// Inserting empty variable;
if( !(empty( $name )) )
<
$sql = "INSERT INTO `users`( name ) VALUE( ‘ $name ‘ );" ;
>
// But is not empty that will be inserted but space
if( !(empty( $name )) )
<
$sql = "INSERT INTO `users`( name ) VALUE( ‘ $name ‘ );" ;
>
// Now that will not be inserted by using trim() function
if( !(empty( trim ( $name ) )) )
<
$sql = "INSERT INTO `users`( name ) VALUE( ‘ $name ‘ );" ;
>
Занимаясь разработкой калькулятора столкнулся с проблемой, что строка типа 1 234 неправильно переводилась в число. В PHP преобразовать строку в число в PHP можно тремя способами. Функцией bool settype (mixed &var, string type) , функцией int intval(mixed var [,int base]) или приведением к типу — (int) или (integer).
Стал пробовать предварительно удалить пробелы в строке функцией str_replace() , но оказалось, что с подобными числами, полученными, например с csv файла функция str_replace() реально НЕ справляется. сам не могу понять почему.
Разбираемся дальше. К пробельным символам относятся символы «
», «
», « », «v», «