Jump to content

Need to check if a string contains an alphabet


tmyonline

Recommended Posts

do you mean an entire alphabet a through to z, or just contains only alphabet characters?

 

use preg_match("/^[a-zA-Z]+$/i",$string);

this function will retru n1 on success or 0 on failure. For help with RegEx use the regex forum.

 

 

hope this helps,

Hi uniflare,

 

I just need to know if my string contains one alphabet out of the alphabetical character set [a-z] case insensitive.  I tried your "preg_match()" and it returned 0.  So, did it tell me that my string did not contain any alphabet ? 

erm, correct me if im wrong but the ^ means "Start of String", so basically match 1 or more ( + ) "A-Z" characters from the start to the end ( $ ) of the string, insensitively (upper & lower case cahracters, i). basically the entire string must consist of a-z characters to match.

 

returning 0 = contains invalid characters

returning 1 = string matched, only contains a-z

 

 

hope this helps,

uniflare, the carot sign "^" means the start of a string if this were in Apache.  In regular expression, as I remember, "^" means the negation of what inside the square bracket [ ].  Anyway, I tried your regular expression with many different strings and they all returns 0.  So,... something is not working!

strange it works for me:

 

<?php
$string = $_GET['string'];

$res = preg_match("/^[a-zA-Z]+$/i",$string);
print_r($res);
?>

 

though im using apache and the carot works for me, is there another way to use a start of string symbol? like the carot symbol, otherwise it would return 1 as long as the last few character were alphabetic.

 

-----

for a botch job (temp fix), you could try:

 

<?php
$string = $_GET['string'];

if(count(preg_match_all("/[a-z]+/i",$string,$matches)) == 1){
   echo("Username: ".$matches[0][0]." is valid");
}else{
echo("username invalid");
}
?>

 

preg_match_all is slightly different to preg_match, it can return higher than 1 (for more than 1 matches), but i assume is slower (as it counts the matches)

 

 

hope this helps,

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.