1

I have a really simple PHP regular expression that isn't returning as a match, as seen below.

if(preg_match('[0-9]{3}','123')){
    echo "match";
}
else{
    echo "nope";
}

This should check if the string '123' matches the pattern '[0-9]{3}', which of course it does - however it's not completing the true condition and is instead echoing "nope".

I've also tried:

if(preg_match('[0-9]{3}' '123') == '1'){
    echo "match";
}
else{
    echo "nope";
}

Any ideas? Do I need to configure my server or enable a regex property / library or something?

1 Answer 1

5

You forget to add the php delimiters.

if(preg_match('~[0-9]{3}~','123')){
Sign up to request clarification or add additional context in comments.

7 Comments

delimiters can anything ~ @ | ... for understanding
Recommend using (...) as delimiters. I do this for two reasons: 1) It subtly reminds me that index 0 of the matched set is the whole match, and 2) they come in matching pairs so you never, ever need to worry about escaping delimiters in the regex itself.
Probably best to use /.../ since that's what most people, at least from the Unix world, expect to see as delimiters.
@AndyLester but it have some problems. I think you need to escape the forward slashes..
Also prefer ~ as delimiter :) Of course it depends on what you're mostly writing the patterns for. There are possibly more cases in general (paths, links,...) where one matches a / than matching literal ~. @NiettheDarkAbsol 2.) For me such as '~\(([^)]+)\)~' is better readable than '(\(([^\)]+)\))' eg to capture parenthesized stuff to $1.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.