Zabs
Zabs

Reputation: 14142

Using Preg Match to check if string contains an underscore

I am trying to check if a string contains an underscore - can anyone explain whats wrong with the following code

    $str = '12_322';
    if (preg_match('/^[1-9]+[_]$/', $str)) {
       echo 'contains number underscore';
    }

Upvotes: 2

Views: 10096

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

In your regex [_]$ means the underscore is at the end of the string. That's why it is not matching with yours.

If you want to check only underscore checking anywhere at the string, then:

if (preg_match('/_/', $str)) {

If you want to check string must be comprised with numbers and underscores, then

if (preg_match('/^[1-9_]+$/', $str)) {  // its 1-9 you mentioned

But for your sample input 12_322, this one can be handy too:

if (preg_match('/^[1-9]+_[1-9]+$/', $str)) {

Upvotes: 9

anubhava
anubhava

Reputation: 786271

You need to take $ out since underscore is not the last character in your input. You can try this regex:

'/^[1-9]+_/'

PS: Underscore is not a special regex character hence doesn't need to be in character class.

Upvotes: 1

Related Questions