Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
    }
like image 240
Zabs Avatar asked Dec 09 '25 09:12

Zabs


1 Answers

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)) {
like image 164
Sabuj Hassan Avatar answered Dec 11 '25 22:12

Sabuj Hassan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!