Php очистить строку от лишних символов

rtrim

Эта функция возвращает строку string с удалёнными из конца строки пробельными (или другими) символами.

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

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

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

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

Возвращает модифицированную строку.

Примеры

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

$text = «\t\tThese are a few words 🙂 . » ;
$binary = «\x09Example string\x0A» ;
$hello = «Hello World» ;
var_dump ( $text , $binary , $hello );

$trimmed = rtrim ( $text );
var_dump ( $trimmed );

$trimmed = rtrim ( $text , » \t.» );
var_dump ( $trimmed );

$trimmed = rtrim ( $hello , «Hdle» );
var_dump ( $trimmed );

// удаляем управляющие ASCII-символы с конца $binary
// (от 0 до 31 включительно)
$clean = rtrim ( $binary , «\x00..\x1F» );
var_dump ( $clean );

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

string(32) " These are a few words :) . " string(16) " Example string " string(11) "Hello World" string(30) " These are a few words :) . " string(26) " These are a few words :)" string(9) "Hello Wor" string(15) " Example string"

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

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

User Contributed Notes 14 notes

I have an obsessive love for php’s array functions given how extremely easy they’ve made complex string handling for me in various situations. so, have another string-rtrim() variant:

function strrtrim ( $message , $strip ) <
// break message apart by strip string
$lines = explode ( $strip , $message );
$last = » ;
// pop off empty strings at the end
do <
$last = array_pop ( $lines );
> while (empty( $last ) && ( count ( $lines )));
// re-assemble what remains
return implode ( $strip , array_merge ( $lines , array( $last )));
>

?>

Astonishingly, something I didn’t expect, but: It completely compares to harmor’s rstrtrim below, execution time wise. o_o Whee!

True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

Here’s a quick way to recursively trim every element of an array, useful after the file() function :

# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file ( «/etc/passwd» );
foreach ( $aFileContent as $sKey => $sValue ) <
$aFileContent [ $sKey ] = rtrim ( $sValue );
>

This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the «new» last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly «rtrimmed» string is returned.
// Example 1:
rtrim ( ‘This is a short short sentence’ , ‘short sentence’ );
// returns ‘This is a’
// If you were expecting the result to be ‘This is a short ‘,
// then you’re wrong; the exact string, ‘short sentence’,
// isn’t matched. Remember, character-by-character comparison!
// Example 2:
rtrim ( ‘This is a short short sentence’ , ‘cents’ );
// returns ‘This is a short short ‘
?>

Читайте также:  Событие onsubmit

I needed a way to trim all white space and then a few chosen strings from the end of a string. So I wrote this class to reuse when stuff needs to be trimmed.

function cleaner ( $cuts , $pinfo ) $ucut = «0» ;
$lcut = «0» ;
while ( $cuts [ $ucut ]) $lcut ++;
$ucut ++;
>
$lcut = $lcut — 1 ;
$ucut = «0» ;
$rcut = «0» ;
$wiy = «start» ;

if (! $cuts [ $ucut ]) $so = «restart» ;
> else $pinfo = rtrim ( $pinfo );
$bpinfol = strlen ( $pinfo );
$tcut = $cuts [ $ucut ];
$pinfo = rtrim ( $pinfo , » $tcut » );
$pinfol = strlen ( $pinfo );

if ( $bpinfol == $pinfol ) $rcut ++;
if ( $rcut == $lcut ) unset( $wiy );
>
$ucut ++;
> else $so = «restart» ;
>
>
>

$pinfo = new cleaner ( $cuts , $pinfo );
$pinfo = $pinfo -> cleaner ;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string. It’s useful for cleaning up comments, articles, or mail that users post to your site, making it so there’s no extra blank space or blank lines.

On the recurring subject of string-stripping instead of character-stripping rtrim() implementations. the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings:

echo basename ( ‘MooFoo’ , ‘Foo’ );

Since it also strips anything that looks like a directory, it’s not quite identical with hacking a string off the end:

echo basename ( ‘Zoo/MooFoo’ , ‘Foo’ );

But sometimes it gets the job done.

I’m sure there’s a better way to strip strings from the end of strings.

/**
* Strip a string from the end of a string
*
* @param string $str the input string
* @param string $remove OPTIONAL string to remove
*
* @return string the modified string
*/
function rstrtrim ( $str , $remove = null )
<
$str = (string) $str ;
$remove = (string) $remove ;

if(empty( $remove ))
<
return rtrim ( $str );
>

> //End of function rstrtrim($str, $remove=null)

echo rstrtrim ( ‘Hello World. ‘ , ‘!’ ) . ‘
‘ ; //»Hello World»
echo rstrtrim ( ‘Hello World. ‘ , ‘!!’ ) . ‘
‘ ; //»Hello World!»
echo rstrtrim ( ‘Hello World. ‘ , ‘. ‘ ) . ‘
‘ ; //»Hello World»
echo rstrtrim ( ‘Hello World. ‘ , ‘. ‘ ). ‘
‘ ; //»Hello World. »
?>

$text = «This string contains some unwanted characters on the end.» ;
$text1 = rtrim ( $text , ‘a..z’ );
$text1 = rtrim ( $text1 , ‘.’ );
echo $text1 ; // only the ‘.’ is trimmed.
$text2 = rtrim ( $text , ‘a..z.’ );
echo $text2 ; // The whole last word is trimmed.
?>

Читайте также:  Summation Of two numbers using PHP

function read_more($in,$len=160) <
if(strlen($in)>$len) <
return preg_replace(‘/[\s\.,][^\s\.,]*$/u’, », substr($in, 0, $len)).’. ‘;
>else <
return $in;
>
>

echo read_mode(«Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.»);
/* Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque. */

To remove an unwanted character — example «.» — if exist or not.

The example above doesn’t include the case where there is no «.»
If there is not «.» at the example above the last word will be deleted.

$text = «This string contains. some unwanted characters on the end .» ;
$text = trim ( $text );
$last = $text < strlen ( $text )- 1 >;
if (! strcmp ( $last , «.» ))
$text = rtrim ( $text , ‘a..z’ );
$text = rtrim ( $text , ‘.’ );
>
?>

Trim limit would be really helpfull. I made a little helper function to do a rtrim with a limited number of replaces:

function rtrim_limit ( $str , $delim , $count = 0 )
if ( $count == 0 ) return rtrim ( $str , $delim );

Источник

trim

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

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

Примеры

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

$text = «\t\tThese are a few words 🙂 . » ;
$binary = «\x09Example string\x0A» ;
$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 );

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

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()

$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() — Заменяет все вхождения строки поиска на строку замены
Читайте также:  Require once object class php

Источник

trim

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

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

Примеры

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

$text = «\t\tThese are a few words 🙂 . » ;
$binary = «\x09Example string\x0A» ;
$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 );

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

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()

$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() — Заменяет все вхождения строки поиска на строку замены

User Contributed Notes 2 notes

note there is a behaviour change in php 8

You used to be able to say:
$p1 = trim($_POST[‘p1’]);
This will now throw deprecated warnings if parameter p1 is not set. It is better to say:
$p1 = trim($_POST[‘p1’]??»);
or
$p1 = isset($_POST[‘p1’]) ? trim($_POST[‘p1’]) : null;
or
$p1 = isset($_POST[‘p1’]) ? trim($_POST[‘p1’]) : »;

Note that trim() is not aware of Unicode points that represent whitespace (e.g., in the General Punctuation block), except, of course, for the ones mentioned in this page.

There is no Unicode-specific trim function in PHP at the time of writing (July 2023), but you can try some examples of trims using multibyte strings posted on the comments for the mbstring extension: https://www.php.net/manual/en/ref.mbstring.php

Источник

Оцените статью