0

I would like to parse user inputs with PHP. I need a function which tells me if there are invalid characters in the text or not. My draft looks as follows:

<?php
function contains_invalid_characters($text) {
    for ($i = 0; $i < 3; $i++) {
        $text = html_entity_decode($text); // decode html entities
    } // loop is used for repeatedly html encoded entities
    $found = preg_match(...);
    return $found;
}
?>

The function should return TRUE if the input text contains invalid characters and FALSE if not. Valid characters should be:

a-z, A-Z, 0-9, äöüß, blank space, "!§$%&/()=[]\?.:,;-_

Can you tell me how to code this? Is preg_match() suitable for this purpose? It's also important that I can easily expand the function later so that it includes other characters.

I hope you can help me. Thanks in advance!

1 Answer 1

3

You could use a regular expression to do that:

function contains_invalid_characters($text) {
    return (bool) preg_match('/[a-zA-Z0-9äöüß "!§$%&\/()=[\]\?.:,;\-_]/u', $text);
}

But note that you need to encode that code with the same encoding as the text you want to test. I recommend you to use UTF-8 for that.

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks! Unfortunately, it returns an "Unknown modifier" error for lots of characters. At first, the error only appears for "(" but when I strip the "(", then it appears also for other characters. Can I escape them so that it works, though?
The / and ] needed to be escaped.
Thank you! Now I get the message "Compilation failed: invalid UTF-8 string at offset 11". This should be due to "äöüß", shouldn't it? How can I encode these characters?
I use UTF-8. I can't replace the pattern by "äöüß", can I?
When you’re using UTF-8 to encode that file, there should be no errors. This error only occurs when your file is not encoded with UTF-8.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.