Prakash Neupane
Prakash Neupane

Reputation: 13

regular expression for matching single characte only

I can't get the regular expression for matching with exactly single character.

$strings=array('hgasdfgh','a','1','addsa');
foreach($strings as $string)
{
$result=preg_match('/[a-z]/',$string);
if($result)
echo "match";
else 
echo "no";}

This code match with 1st 2nd and 4th string of array. But i need it for just match with 2nd item(any character).

Upvotes: 1

Views: 81

Answers (2)

FailedDev
FailedDev

Reputation: 26930

/[a-z]/

So what does this mean? Match a single character from a-z.

All your array entries except the 3rd one fulfill this requirement. Therefore all match.

Now if you were to enclose your regex in anchors :

/^[a-z]$/

It would only match the beginning of the string, followed by a single letter, followed by the end of the string i.e. your second entry in the array.

Edit :

You asked for the difference of ^ inside and outside of a bracket :

When ^ is outside a bracket, alone it means the beginning of the string. If you escape it \^ it means to match the character ^ literally.

When ^ is inside the bracket(s) such as :

[^a-z] it effectively negates this character class, meaning that you should match something which is NOT a character in the rance a-z. So this could match for example 9, A, # etc. Finally when ^ is inside a character class but not in the first position :

[a-z^] it loses it's special meaning of negation and it is a literal ^ character. So the character class now matches either a single character from the range a-z or ^.

Upvotes: 2

ComFreek
ComFreek

Reputation: 29424

Try this expression

^[a-z]$

^ indicates the beginning of the string and $ the end of it.

Upvotes: 2

Related Questions