Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading