Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim special chars from string?

Tags:

regex

php

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)
like image 878
Adam Pietrasiak Avatar asked Mar 23 '23 07:03

Adam Pietrasiak


1 Answers

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Ó~~' );
like image 55
anubhava Avatar answered Apr 02 '23 19:04

anubhava