Skip to content
Advertisement

trim() leaves a single trailing and leading space

php 7.4

I believe php’s trim is malfunctioning. It removes duplicate trailing and leading spaces, but it leaves a single trailing and leading space.

function string_to_safe_list($str){
    $list = explode(",", $str);
    array_map(function($x){
        return trim(strtolower(htmlspecialchars($x)));
    }, $list);
    var_dump($str);
    var_dump($list);
    return $list;
}
$str = "test,test, test, test   ,  test, test";
=> string_to_safe_list($str) = {"test", "test", " test", " test ", " test", " test"}

$str is a “comma seperated value” array.

How can I get trim() to behave properly and thus get $list to become {"test", "test", "test", "test", "test", "test"}, without manually checking and correcting the first and last character of each string in $list?

It is unacceptable to delete every single whitespace instance however, because a valid $str might be "test entry, test entry, test, test" which should become {"test entry", "test entry", "test", "test"}

Advertisement

Answer

You have to assign the result of array_map to a variable.

function string_to_safe_list($str){
    $list = explode(",", $str);
    $list = array_map(function($x){
        return trim(strtolower(htmlspecialchars($x)));
    }, $list);
    return $list;
}

$str = "test,test, test, test   ,  test, test";

var_dump(string_to_safe_list($str));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement