Opcionalmente, os caracteres removidos também podem ser especificados usando
o parâmetro characters.
Simplesmente liste todos os caracteres que precisam ser removidos.
Com .. é possível especificar um intervalo incremental de caracteres.
// retira os caracteres ASCII de controle no início e fim de $binary // (de 0 a 31 inclusive) $clean = trim($binary, "\x00..\x1F"); var_dump($clean);
?>
O exemplo acima produzirá:
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"
Exemplo #2 Usando trim() em valores de array
<?php function trim_value(&$value) { $value = trim($value); }
Nota:
Possível armadilha: removendo caracteres no meio da string
Como trim() retira caracteres do início de do fim de
uma string, pode ser confuso quando caracteres são (ou não) removidos do
meio. trim('abc', 'bad') remove tanto 'a' quanto 'b' porque ele retira
'a', portanto move 'b' para o início e também será retirado. Portanto, este é o motivo pelo qual isso "funciona"
enquanto que trim('abc', 'b') aparentemente não funciona.
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