Php trim text html

PHP trim

Summary: in this tutorial, you’ll learn how to use the PHP trim() function to remove whitespace or other characters from both ends of a string.

Introduction to the PHP trim() function

The trim() function removes the whitespaces or other characters from the beginning and end of a string.

Here’s the syntax of the trim() function:

trim ( string $string , string $characters = " \n\r\t\v\0" ) : stringCode language: PHP (php)

The trim() function has two parameters:

  • $string is the input string that will be trimmed.
  • $characters argument is optional. It specifies which character to remove from both ends of the $string .

By default, the trim() function removes the following characters:

Character ASCII Hex Description
” “ 32 0x20 a space
“\t” 9 0x09 a tab
“\n” 10 0x0A a new line
“\r” 13 0x0D a return
“\0” 0 0x00 a NUL-byte
“\v” 11 0x0B a vertical tab

If you want to remove other characters, you can specify them in the $characters argument.

To specify a range of characters to remove, you can use the ‘..’. For example, to remove all ASCII control characters from both ends of a string, you use the following value for the $characters argument:

'\x00..\x1F'Code language: PHP (php)

It’s important to note that the trim() function doesn’t change the input string. It returns a new string with all the $characters removed.

Читайте также:  Php url get undefined index

PHP trim() function examples

Let’s take some examples of using the PHP trim() function.

1) Using the PHP trim() function to remove whitespace from both ends of a string

The following example uses the trim() function to remove spaces from the beginning and the end of a string:

 $str = ' PHP '; $new_str = trim($str); var_dump($new_str);Code language: PHP (php)
string(3) "PHP"Code language: plaintext (plaintext)

2) Using the PHP trim() function to remove other characters

Suppose you have the following URL:

https://www.phptutorial.net/api/v1/posts/Code language: PHP (php)

To get the request URI, you access the $_SERVER array with the key ‘REQUEST_URI’ :

 $uri = $_SERVER['REQUEST_URI']; echo $uri;Code language: PHP (php)
/api/v1/posts/Code language: plaintext (plaintext)

The URI contains both leading and trailing slashes.

To remove the slashes ( / ) from both ends of the URI, you can use the trim() function:

 $uri = $_SERVER['REQUEST_URI']; echo trim($uri,'/');Code language: PHP (php)
api/v1/postsCode language: plaintext (plaintext)

Summary

  • Use the PHP trim() function to remove whitespaces or other characters from both ends of a string.

Источник

PHP trim() Function

Remove characters from both sides of a string («He» in «Hello» and «d!» in «World»):

Definition and Usage

The trim() function removes whitespace and other predefined characters from both sides of a string.

  • ltrim() — Removes whitespace or other predefined characters from the left side of a string
  • rtrim() — Removes whitespace or other predefined characters from the right side of a string

Syntax

Parameter Values

  • «\0» — NULL
  • «\t» — tab
  • «\n» — new line
  • «\x0B» — vertical tab
  • «\r» — carriage return
  • » » — ordinary white space

Technical Details

Return Value: Returns the modified string
PHP Version: 4+
Changelog: The charlist parameter was added in PHP 4.1

More Examples

Example

Remove whitespaces from both sides of a string:

The HTML output of the code above will be (View Source):

Without trim: Hello World!
With trim: Hello World!

The browser output of the code above will be:

Example

Remove newlines (\n) from both sides of the string:

$str = «\n\n\nHello World!\n\n\n»;
echo «Without trim: » . $str;
echo «
«;
echo «With trim: » . trim($str);
?>

The HTML output of the code above will be (View Source):

The browser output of the code above will be:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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

Источник

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

Источник

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