Forum Moderators: coopster

Message Too Old, No Replies

Testing Strings

For A-Z and Hyphens

         

unperturbed

3:03 pm on Jun 12, 2007 (gmt 0)

10+ Year Member



Hi,
How can I check a string is just made up of letters and hyphens. I've looked at preg_match etc but they don't seem to test for only letters and numbers.

Cheers.

barns101

4:01 pm on Jun 12, 2007 (gmt 0)

10+ Year Member



preg_match should work, as long as your pattern is correct. I've not used preg_match myself but a pattern along the lines of ([a-z0-9]+) should match an alphanumeric string.

whoisgregg

4:43 pm on Jun 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A regex along the lines of
([a-zA-Z-]+)
should match just letters and hyphens.

unperturbed

12:52 am on Jun 13, 2007 (gmt 0)

10+ Year Member



Thanks guys i got a bit confused in the OP started of saying letters and hyphens, then went on to mention letters and numbers. What I'm really after letters and hyphens.

I'm using this code to test.

if (preg_match("([a-zA-Z-]+)", "abc")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

which finds a match but it also finds a match with.

if (preg_match("([a-zA-Z-]+)", "abc123")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

Which i don't want it to.

Cheers

coopster

3:16 am on Jun 13, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can negate the pattern:
$pattern = "/[^a-zA-Z-]/";

unperturbed

12:38 pm on Jun 13, 2007 (gmt 0)

10+ Year Member



Thanks coopster,

Using the following code seems to work now, thank you.

if (preg_match("/[^a-zA-Z-]/", "abc")) {
echo "A match was not found.";
} else {
echo "A match was found.";
}