简体   繁体   中英

Regular expression to validate one or more letters

I have been trying to get regular expressions to work in PHP for quite some time now. The problem is that it doesn't accept things that it should and while accepting text that it shouldn't. I tried different expressions from the internet since I probably didn't write them correct myself. It still didn't work, no mather how trivial expressions I tried so I assumed that there were other things in my code that was causing these problems. I therefor reduce my code to the bare minimum, but still it does not work and I can't understand why.

What I really want is to check if the text only contains numbers, letters and a few special characters, but to make sure that the expression itself wasn't the problem, I used the simplest expression I could find; just checking for letters. I have tried many things, like writing the pattern inside the function instead of saving it as a variable etc but nothing helped. This is the code as it looks now, all of it.

<?php

$pattern = "/^[a-z]$/";

if($_POST && !empty($_POST['input']))
{
    if(preg_match($pattern, $_POST['input']))
    {
        echo 'Correct';
    }
    else
    {
        echo 'Wrong';
    }
}
?>

<html>
<body>

<form method="post" action="">
<p><input type="text" name="input"></p>
<p><input type="submit" name="submit"></p>
</form>

</body>
</html>

Help would be greatly appreciated!

This expression checks for single letter only. Change

$pattern = "/^[az]$/";

To

$pattern = "/^[az]+$/";

/^[a-z]$/

This will accept only a string with one character.

try:

/^[a-z]+$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM