I want to allow only certain characters in a string, I know it\'s easy with preg_match but this function I couldn\'t understand it from years :/
As
You need to learn about regular expressions first. They are a general concept in programming, and there's better places to read about them than PHP manual. Try regular-expressions.info.
For your specific question, you need character class pattern: [...]
will match any of the characters inside the brackets. If you write it with a hat at the start, it will match any character that is not in the brackets: [^...]
. You want to replace all the non-matching characters with nothing, so you can use the function preg_replace
:
preg_replace("/[^...]/gu", "");
The slashes are required separators (slashes are traditional, but there's other things you can use), the "g" means "global", as in "replace all occurences, not just the first one", and "u" means "unicode", which will allow you to catch the Arabic characters and that weird special character at the end.
Now, you could list all the characters where I've put the dots; or you can specify character ranges. For example, [^a-zA-Z0-9,.\/+&-]
matches any alphanumeric English character, and all of the special characters except the weird one at the end :p . Notice that you need to escape the slash with a backslash (because otherwise it would terminate the regular expression), and you need to have the minus sign as last (otherwise it would be interpreted as a character range). You can extend for other languages as appropriate (I am not familiar enough with encoding of Arabic).