Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

regex - PHP Regular expression - Remove all non-alphanumeric characters

I use PHP.

My string can look like this

This is a string-test width ??? and some über+strange characters: _like this?

Question

Is there a way to remove non-alphanumeric characters and replace them with a space? Here are some non-alphanumeric characters:

  • -
  • +
  • :
  • _
  • ?

I've read many threads about it but they don't support other languages, like this one:

preg_replace("/[^A-Za-z0-9 ]/", '', $string);

Requirements

  • My list of none letter characters might not be complete.
  • My content contain characters in different languages, like ???ü. Could be very many more.
  • The non-alphanumeric characters should be replaced with a space. Else the word would be glued to eachother.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try this:

preg_replace('~[^p{L}p{N}]++~u', ' ', $string);

p{L} stands for all alphabetic characters (whatever the alphabet).

p{N} stands for numbers.

With the u modifier characters of the subject string are treated as unicode characters.

Or this:

preg_replace('~P{Xan}++~u', ' ', $string);

p{Xan} contains unicode letters and digits.

P{Xan} contains all that is not unicode letters and digits. (Be careful, it contains white spaces too that you can preserve with ~[^p{Xan}s]++~u )

If you want a more specific set of allowed letters you must replace p{L} with ranges in unicode table.

Example:

preg_replace('~[^a-zà-??-???d]++~ui', ' ', $string);

Why using a possessive quantifier (++) here?

~P{Xan}+~u will give you the same result as ~P{Xan}++~u. The difference here is that in the first the engine records each backtracking position (that we don't need) when in the second it doesn't (as in an atomic group). The result is a small performance profit.

I think it's a good practice to use possessive quantifiers and atomic groups when it's possible.

However, the PCRE regex engine makes automatically a quantifier possessive in obvious situations (example: a+b => a++b) except If the PCRE module has been compiled with the option PCRE_NO_AUTO_POSSESS. (http://www.pcre.org/pcre.txt)

More informations about possessive quantifiers and atomic groups here (possessive quantifiers) and here (atomic groups) or here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...