PHP: allow only certain characters in a string, without using regular expressions

I want to allow only some characters in a string, I know that it is easy with preg_match , but I could not understand this function from year: /

As I said, I saw millions of preg_match examples, but I want to create mine, I want to allow only:

1) all upper / lower English letters and numbers

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890

2) all Arabic letters and numbers

اأإآبتثحخدذرزسشصضطظعغفقكلمنهويىءئ 1234567890

3) the following special characters

, () / - + &.,

Anything else I want to delete.

+4
source share
1 answer

First you need to learn about regular expressions. They represent a general programming concept, and there is better place to read than the PHP manual. Try regular-expressions.info .

For your specific question, you will need a character class template: [...] will match any of the characters inside the brackets. If you write it with a hat at the beginning, it will match any character that is not in brackets: [^...] . You want to replace all non-matching characters with nothing, so you can use the preg_replace function:

 preg_replace("/[^...]/gu", ""); 

Traits are required for delimiters (slashes are traditional, but there are other things you can use), "g" means "global", like "replace all occurrences, not just the first one", and "u" means "unicode", which allows you to catch arabic characters and this strange special character at the end.

Now you can list all the characters where I put the dots; or you can specify ranges of characters. For example, [^a-zA-Z0-9,.\/+&-] matches any alphanumeric English character and all special characters except the weird one at the end: p. Note that you need to avoid the backslash (because otherwise it will cause the regular expression to stop), and you must have a minus sign as the last one (otherwise it will be interpreted as a range of characters). You can distribute to other languages ​​as needed (I am not familiar enough with the Arabic encoding).

+6
source

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


All Articles