Unexpected behaviour with PHP trim() native function

Is this for real?

Native PHP trim function uses the $char_double by default. I expected the $trimmed_single_double to be as $trimmed_matching_double.
This code was tested on https://onlinephp.io/c/9799e2b3-6598-447b-9ca1-31218983d9e1 using (PHP 8.1.12). Feel free go check it out.

I want to believe I’m doing something wrong. I’m nervous.

Code (PHP 8.1.12)

<?php

$text_double = "\n text \n";
$text_single = '\n text \n';

$char_double = " \t\n\r\0\x0B";
$char_single = ' \t\n\r\0\x0B';

$trimmed_matching_double = trim($text_double, $char_double);
$trimmed_matching_single = trim($text_single, $char_single);
$trimmed_single_double = trim($text_single, $char_double);

var_dump([
    'trimmed_matching_double' => $trimmed_matching_double, 
    'trimmed_matching_single' => $trimmed_matching_single,
    'trimmed_single_double' => $trimmed_single_double,
]);

Output

array(3) {
  ["trimmed_matching_double"]=>
  string(4) "text"
  ["trimmed_matching_single"]=>
  string(1) "e"
  ["trimmed_single_double"]=>
  string(10) "\n text \n"
}

Please shed some light on this. Thank you!

>Solution :

When you use single quotes in PHP:

escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning

So:
When you trim single with single, it will remove all characters ('\', 'n', ' ', 't', etc.)

When you try to remove double with single, it find nothing, because '\n' is considered a single character. He cannot fina a single '\' or a single 'n'.

Leave a Reply