Συναρτήσεις trim() του PHP

Παράδειγμα

Αφαίρεση χαρακτήρων από τις δύο πλευρές της συμβολοσειράς (στο "Hello" ο "He" και στο "World" ο "d!"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

Run Instances

Ορισμός και χρήση

Η συναρτήση trim() αφαιρεί λευκούς χαρακτήρες ή άλλους προκαθορισμένους χαρακτήρες από τις δύο πλευρές της συμβολοσειράς.

Συσχετιζόμενες συναρτήσεις:

  • ltrim() - Αφαίρεση λευκών χαρακτήρων ή άλλων προκαθορισμένων χαρακτήρων από τη αριστερή πλευρά της συμβολοσειράς.
  • rtrim() - Αφαίρεση λευκών χαρακτήρων ή άλλων προκαθορισμένων χαρακτήρων από τη δεξιά πλευρά της συμβολοσειράς.

Γλώσσα

trim(s
tring,charlist)
Παράμετρος Περιγραφή
string Απαιτείται. Ορίζει τη συμβολοσειρά που πρέπει να ελεγχθεί.
charlist

Optional. Specifies which characters to remove from the string. If omitted, the following characters are removed:

  • "\0" - NULL
  • "\t" - Tab
  • "\n" - Newline
  • "\x0B" - Vertical tab
  • "\r" - Carriage return
  • " " - Space

Technical Details

Return value: Returns the modified string
PHP Version: 4+
Update Log: In PHP 4.1, a new feature was added charlist Parameter.

More Examples

Example 1

Remove spaces from both sides of the string:

<?php
$str = " Hello World! ";
echo "Do not use trim: " . $str;
echo "<br>";
echo "Use trim: " . trim($str);
?>

The HTML output of the above code is as follows (please view the source code):

<!DOCTYPE html>
<html>
<body>
Do not use trim:  Hello World! <br>Use trim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use trim: Hello World!
Use trim: Hello World!

Run Instances

Example 2

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

<?php
$str = "\n\n\nHello World!\n\n\n";
echo "Do not use trim: " . $str;
echo "<br>";
echo "Use trim: " . trim($str);
?>

The HTML output of the above code is as follows (please view the source code):

<!DOCTYPE html>
<html>
<body>
Do not use trim:
Hello World!
<br>Use trim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use trim: Hello World!
Use trim: Hello World!

Run Instances