How to trim special chars from string?

How to trim special chars from string?

I want to remove all non-alphanumeric signs from left and right of the string, leaving the ones in middle of string.

I’ve asked similar question here, and good solution is:

$str = preg_replace('/^W*(.*w)W*$/', '$1', $str);

But it does remove also some signs like ąĄćĆęĘ etc and it should not as its still alphabetical sign.

Above example would do:

~~AAA~~  => AAA (OK)
~~AA*AA~~ => AA*AA (OK)
~~ŚAAÓ~~  => AA (BAD)

Make sure you use u flag for unicode while using your regex.

Following works with your input:

$str = preg_replace('/^W*(.*w)W*$/u', '$1', '~~ŚAAÓ~~' );

// str = ŚAAÓ

But this won’t work: (Don’t Use it)

$str = preg_replace('/^W*(.*w)W*$/', '$1', '~~ŚAAÓ~~' );