trim()任何不是字母或数字的前导或拖尾字符[重复]

This question already has an answer here:

How can i trim() the following sentence

,, This is New, A new Sentence.,

to become

This is New, A new Sentence

I've tried trim() and rtrim() together and didn't work either,

$str = ",, This is New, A new Sentence., ";
$str = trim(rtrim($str));

result was always the same with or together trim and rtrim() ,, This is New, A new Sentence.,

Is it possible to handle this using trim() function?

In case the solution is using preg_replace(), Then the current RegEx i use is preg_replace('/[\s,]+/',',',trim(rtrim($str)))

</div>

Try the following:

$str = ",, This is New, A new Sentence., ";
$str = trim(preg_replace("/^[^A-Za-z0-9]+|[^A-Za-z0-9]+$/", '', $str));

var_dump($str);

And to use /[\s,]+/ too, try the following:

$str = trim(preg_replace_callback_array([
    "/^[^A-Za-z0-9]+|[^A-Za-z0-9]+$/" => function($match){}, 
    "/[\s,]+/" => function ($match)
    {
        return ",";
    }
    ], $str));

the regex will remove all trailing and leading chars from the string, that are not alphanumeric. And trim() will remove the whitespace

It's a question of business logic, i.e. the aim. In your case it seems to be:

The start and end of the string should be a letter (or presumably number).

In which case, via REGEX, strip off anything violating this.

preg_replace('/^[^a-z0-9]+|[^a-z0-9]+$|[\s,]{2,}/i', '', $str);