Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a string only contains A-Z, a-z and - (dash) characters using preg_match [duplicate]

Tags:

regex

php

I've tried:

print_r(preg_match("[A-Za-z\\-]", $str));

And I'm getting false. I'm not very good at regex but it seems to work on http://regexpal.com/

Am I missing something here?

EDIT: e.g. $str = zREBsZtyvw

like image 322
meiryo Avatar asked Dec 11 '22 14:12

meiryo


2 Answers

Description

This expression will ensure you have 1 or more uppercase, lower case, or hypens in the the string with no whitespace

^[A-Za-z\\-]{1,}$

enter image description here

Match Pattern Explanation:

(^[A-Za-z\\-]{1,}$)

matches as follows:

( group

^ the beginning of the string

[A-Za-z\\-]{1,} any character of: 'A' to 'Z', 'a' to 'z', '\', '-' (at least 1 times (matching the most amount possible))

$ before an optional \n, and the end of the string

) end of grouping

PHP Code Example:

<?php
$sourcestring="zREBsZtyvw";
preg_match_all('/^[A-Za-z\\-]{1,}$/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

$matches Array:
(
    [0] => Array
        (
            [0] => zREBsZtyvw
        )

)
like image 50
Ro Yo Mi Avatar answered Feb 15 '23 10:02

Ro Yo Mi


Jerry and Yomy each identified half the problem. Here's the whole solution:

print_r(preg_match("/^[A-Za-z\\-]*$/", $str));

preg_match requires you to have matching delimiters at the beginning and end of the regexp. And you need to anchor the regexp so that it will check the whole string, not just look for a match anywhere in the strong. And you need to use the * wildcard to match any number of characters.

like image 23
Barmar Avatar answered Feb 15 '23 11:02

Barmar