How to trim special characters from a string?

I want to remove all non-alphanumeric characters to the left and right of the line, leaving them in the middle of the line.

I asked a similar question here , and a good solution:

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

But he also removes some signs, such as ĄĄćĆęĘ, etc., and he should not be his alphabetical sign.

Example above:

 ~~AAA~~ => AAA (OK) ~~AA*AA~~ => AA*AA (OK) ~~ŚAAÓ~~ => AA (BAD) 
+4
source share
2 answers

Make sure you use the u flag for Unicode using a regex.

After working with your input:

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

But this will not work: (Do not use it)

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

You can pass a list of valid characters and tell the function to replace any character that is not in this list:

$str = preg_replace('/[^a-zA-Z0-9*]+/', '', $str);

Square brackets say select everything in this range. Carat ( ^ ) is a regular expression for no. Then we list our valid characters (lowercase from a to z, uppercase from a to z, numbers 0 to 9, and asterisks). A plus sign at the end of the square bracket indicates that 0 or more characters are selected.

Edit:

If this is a list of all the characters you want to keep, then:

$str = preg_replace('/[^ĄąĆćŻżŹźŃńŁłÓó*]+/', '', $str);

+3
source

Source: https://habr.com/ru/post/1489666/


All Articles