1

I want a variable that allow letters and only, not digits.

And that variable can be at any position in the string.

Look at this,

$pattern = '~user/(:var)~';

$pattern = str_replace('(:var)', '([a-zA-Z])', $pattern);

// Note, the variable contain both numbers and letters
$test = 'user/dave123';

$r = preg_match($pattern, $test); 

var_dump($r); //1 Success (I don't want this)

All I want is,

If a variable contain letters only, then preg_match() should return 1, but if that one contains at least one digit, then preg_match() should immediately return 0,

What regex should be defined instead of ([a-zA-Z]) and why ([a-zA-Z]) matches both numbers and letters!?

4

4 に答える 4

6

The regular expression is matching this substring of your test value: user/d.

If you want to check against the whole string, add start (^) and end ($) anchors to your pattern:

$pattern = '~^user/(:var)$~';

To check against the start/end of a string OR another delimiter such as /, it would look like this:

$pattern = '~(?:^|/)user/(:var)(?:$|/)~';

This will force it to consider the entire value up until either the end of the string or the next /... preventing partial matches like you encountered in your question.

(The ?: indicates a non-capturing group, which means that the extra () groups won't end up in your resulting list of matches)

You'll also need to allow the [a-zA-Z] class to repeat with +, or it will only match single-character usernames:

$pattern = str_replace('(:var)', '([a-zA-Z]+)', $pattern);
于 2013-06-17T04:27:15.843 に答える
3

^それぞれとを使用してエンディングを開始する必要があり$ます。

'~^user/(:var)$~'

user文字列に ,があるため、一致daveします。

于 2013-06-17T04:27:32.493 に答える
1

あなたのパターンは「azまたはAZの間の任意の文字の1つ」を意味するため、一致します。それが一致する唯一のものであるかどうかを確認するチェックは提供されず、繰り返される文字とは一致しません。

そのアプローチの代わりに、もっと簡単なことを試してみませんか。知りたいのは、文字列に数字が含まれているかどうかだけなので:

$haystack = 'user/dave123';
foreach(range(0,9) as $i) {
    if (strpos($haystack,$i) === FALSE)) {
         return 1;
    }
}
return 0;

これは、見つかった最初の番号で停止します。

于 2013-06-17T04:35:02.980 に答える
0

パターンが文字列の最初の文字に一致し、文字列全体には一致しない可能性があります。文字列全体と照合するには、試してください

"/^[a-z]+$/i"

これにより、大文字と小文字を区別しない文字が文字列全体でのみ一致します(文字列の開始と文字^列の 区切り文字の終了です)。$

ctype_alpha()まったく同じことを行う便利な組み込み PHP 関数もいくつかあります。

于 2013-06-17T04:31:10.747 に答える