开发者

Attempting to understand handling regular expressions with php

I am trying to make sense of handling regular expression with php.开发者_运维问答 So far my code is:

PHP code:

$string = "This is a 1 2 3 test.";

$pattern  = '/^[a-zA-Z0-9\. ]$/';
$match = preg_match($pattern, $string);

echo "string: " . $string . " regex response: " , $match; 

Why is $match always returning 0 when I think it should be returning a 1?


[a-zA-Z0-9\. ] means one character which is alphanumeric or "." or " ". You will want to repeat this pattern:

$pattern  = '/^[a-zA-Z0-9. ]+$/';
                            ^
                      "one or more"

Note: you don't need to escape . inside a character group.


Here's what you're pattern is saying:

  • '/: Start the expressions
  • ^: Beginning of the string
  • [a-zA-Z0-9\. ]: Any one alphanumeric character, period or space (you should actually be using \s for spaces if your intention is to match any whitespace character).
  • $: End of the string
  • /': End the expression

So, an example of a string that would yield a match result is:

$string = 'a'

Of other note, if you're actually trying to get the matches from the result, you'll want to use the third parameter of preg_match:

$numResults = preg_match($pattern, $string, $matches);


You need a quantifier on the end of your character class, such as +, which means match 1 or more times.

Ideone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜