Regex Problem in PHP

I'm attempting to utilize the following Regex pattern:

$regex = '/Name: [a-zA-Z ]*] [0-9]/';

When testing it in Rubular, it works fine, but when using PHP the expression never returns true, even when it should. Incidentally, if I remove the "[0-9]" part, it works fine. Is there some difference in PHP's regex syntax that I'm overlooking?

Edit: I'm looking for the characters "Name:" then a name containing any number of letters or spaces, then a "]", then a space, then a single number. So "Name: Chris] 5" would return true and "Name: Chris] [lorem ipsum]" should return false.

I also tried escaping the second bracket " [ " but this did not fix the problem.


It's not clear without examples what your use case, but it seems like you want something like this?

$regex = '/Name: ([w]+) ([w]+)/';

Update: try this:

$regex = '/Name: [ws]+?] [d]{1}/';

For me this matches

Name: Foo Bar] 2

..but not these:

Name: Foo Bar] foo
Name: Foo Baz 5

I'm also using short-hand expressions for character classes:

  • [w] is short for [a-zA-Z0-9] ( eg all alphanumeric characters )
  • [s] matches any whitespace
  • [d] matches any number
  • For safety I'm also using the '?' to match in a non-greedy way, to make sure thw [ws]+ match doesn't consume too much of the string.


    i think this might be because of the space in the regex also u want to escape the second ]. try

    $regex = '/Name:s[a-zA-Z ]*]s[0-9]/';
    

    Or use a modifier

    $regex = '/Name: [a-zA-Z ]*] [0-9]/x';
    

    more on modifiers here PHP: Possible modifiers in regex patterns - Manual


    Your regex works nicely for me with the two examples you gave.

    $arr = array('Name: Chris] 5', 'Name: Chris] [lorem ipsum]');
    foreach ($arr as $str) {
        if (preg_match('/Name: [a-zA-Z ]*] [0-9]/', $str)) {
            echo "$str : OKn";
        } else {
            echo "$str : KOn";
        }
    }
    

    Output:

    Name: Chris] 5 : OK
    Name: Chris] [lorem ipsum] : KO
    

    May be there are more than one space between ] and the digit, so your regex should be:

    [a-zA-Z ]*]s+[0-9]/
    
    链接地址: http://www.djcxy.com/p/92696.html

    上一篇: 正则表达式来检查多个

    下一篇: PHP中的正则表达式问题