Progress28.ru

IT Новости
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Php trim string

Php trim string

(PHP 4, PHP 5, PHP 7)

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

Описание

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

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

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

Примеры

Пример #1 Пример использования trim()

= «ttThese are a few words 🙂 . » ;
$binary = «x09Example stringx0A» ;
$hello = «Hello World» ;
var_dump ( $text , $binary , $hello );

$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 );

Результат выполнения данного примера:

Пример #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 , » tnr» ); // $trimmed_incorrect = trim ( $hello , ‘ tnr’ ); // 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!
?>

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» or «xc2xa0» in utf-8, «µ» is «u» or «xc2xb5» in utf-8 and «à» is «u» or «xc3xa0» in utf-8

$input = «uµ déjàu«; // » µ déjà «
$output = trim($input, «u«); // «▒ déj▒» or whatever how the interpretation of broken utf-8 characters is performed

$output got both «u» characters removed but also both «µ» and «à» characters destroyed

To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

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 «n $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 ;
>

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»).]

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.

Читать еще:  Php и sql

there should be no spaces at the beginning and end of your echo statement, else trim will not work as expected.

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 ‘ );» ;
>

Php trim string

(PHP 4, PHP 5, PHP 7)

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

Описание

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

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

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

Примеры

Пример #1 Пример использования trim()

= «ttThese are a few words 🙂 . » ;
$binary = «x09Example stringx0A» ;
$hello = «Hello World» ;
var_dump ( $text , $binary , $hello );

$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 );

Результат выполнения данного примера:

Пример #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 , » tnr» ); // $trimmed_incorrect = trim ( $hello , ‘ tnr’ ); // 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!
?>

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» or «xc2xa0» in utf-8, «µ» is «u» or «xc2xb5» in utf-8 and «à» is «u» or «xc3xa0» in utf-8

Читать еще:  Php num rows

$input = «uµ déjàu«; // » µ déjà «
$output = trim($input, «u«); // «▒ déj▒» or whatever how the interpretation of broken utf-8 characters is performed

$output got both «u» characters removed but also both «µ» and «à» characters destroyed

To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this:

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 «n $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 ;
>

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»).]

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.

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 ‘ );» ;
>

php trim a string

I’m trying to build a function to trim a string is it’s too long per my specifications.

Here’s what I have:

The above will trim a string if it’s longer than the $max and will add a continuation .

I want to expand that function to handle multiple words. Currently it does what it does, but if I have a string say: How are you today? which is 18 characters long. If I run trim_me($s,10) it will show as How are yo. , which is not aesthetically pleasing. How can I make it so it adds a . after the whole word. Say if I run trim_me($s,10) I want it to display How are you. adding the continuation AFTER the word. Any ideas?

I pretty much don’t want to add a continuation in the middle of a word. But if the string has only one word, then the continuation can break the word then only.

4 Answers 4

So, here’s what you want:

strrpos is the function that does the magic.

I’ve named the function str_trunc . You can specify strict being TRUE, in which case it will only allow a string of the maximum size and no more, otherwise it will search for the shortest string fitting in the word it was about to finish.

Читать еще:  Выбор плавкого предохранителя для защиты трансформатора

It’s actually somehow simple and I add this answer because the suggested duplicate does not match your needs (but it does give some pointers).

What you want is to cut a string a maximum length but preserve the last word. So you need to find out the position where to cut the string (and if it’s actually necessary to cut it at all).

As getting the length ( strlen ) and cutting a string ( substr ) is not your problem (you already make use of it), the problem to solve is how to obtain the position of the last word that is within the limit.

This involves to analyze the string and find out about the offsets of each word. String processing can be done with regular expressions. While writing this, it reminds me on some actually more similar question where this has been already solved:

It does exactly this: Obtaining the «full words» string by using a regular expression. The only difference is, that it removes the last word (instead of extending it). As you want to extend the last word instead, this needs a different regular expression pattern.

In a regular expression b matches a word-boundary. That is before or after a word. You now want to pick at least $length characters until the next word boundary.

As this could contain spaces before the next word, you might want to trim the result to remove these spaces at the end.

You could extend your function like the following then with the regular expression pattern ( preg_replace ) and the trim :

You can further on extend this by reducing the minimum length in the pattern by the length of the suffix (as it’s somehow suggested in your question, however the results you gave in your question did not match with your code).

I hope this is helpful. Also please use the search function on this site, it’s not perfect but many gems are hidden in existing questions for alternative approaches.

How to Trim Strings in PHP

All trimming functions are used to remove any whitespaces from the starting and end of the string. The following characters are considered as whitespace in PHP. The particular character range can be used without these whitespace characters.

“n” — newline character

“t” — tab character

“r” — carriage return character

“” — vertical tab character

“x0B” – null-byte character

Example-1: trim() function

trim() function can take two inputs as argument values. First argument is mandatory and second argument is optional. If the optional argument value is omitted then the function will remove space from the starting and ending part the value provided by the first argument. In the following example, there are multiple spaces at the starting and the ending of the variable $str1 and trim function is applied for $str1 without the optional parameter. “rn” whitespaces are included in the variable $str2 and “rn” is used as second argument value of trim() function. In this case, trim() function will remove all “rn” whitespaces from both side of the variable $str2. Range values can be used as second argument value. There are numeric values on both side of the variable $str3 and numeric range 0..9 is used as second argument value of trim() function to remove numeric part from both side of the variable $str3.

$str1 = » I like programming » ;

//using trim() function without optional value
echo trim ( $str1 ) . «
» ;
$str2 = » r n PHP is a popular programming language r n » ;

//using trim() function with “rn” as optional value
echo trim ( $str2 , » r n » ) . «
» ;
$str3 = «123 linuxhint.com 890» ;

//using trim() function with numeric range as optional value
echo trim ( $str3 , «0..9» ) . «
» ;
?>

Output:

Example-2: ltrim() and rtrim() functions

ltrim() and rtrim() functions are identical to trim() function. ltrim() removes whitespaces or other specific characters from the left side and rtrim() removes whitespaces or other specific characters from the right side of any string value. In the following example, ltrim() and rtrim() are applied on two variables, $Str1 and $Str2 with and without optional value.

$Str1 = » PHP is a popular language » ;
$Str2 = «02JavaScript is client-side scripting language99» ;

//using ltrim() function
echo «Output of ltrim() without optional value: » . ltrim ( $Str1 ) . «
» ;
echo «Output of ltrim() with optional value: » . ltrim ( $Str2 , «0..9» ) . «

//using rtrim() function
echo «Output of rtrim() without optional value: » . rtrim ( $Str1 ) . «
» ;
echo «Output of rtrim() with optional value: » . rtrim ( $Str2 , «0..9» ) . «
» ;

Output:

You will need to use trimming functions in your PHP program based on the requirement for getting the appropriate output. I hope this tutorial will help you to understand the use of trimming functions and apply them properly in your PHP script.

About the author

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Ссылка на основную публикацию
Adblock
detector