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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…