Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate variables in a regular expression string with preg_match()

Tags:

regex

php

I'm using preg_match() function which determines whether a function is executed.

if( preg_match( '/^([0-9]+,){0,3}[0-9]+$/', $string ) ) { ... }

However I have to use a integer variable and integrate it in the regular expression:

$integer = 4;
if( preg_match( '/^([0-9]+,){0,' . $integer . '}[0-9]+$/', $string ) ) { ... }

but it doesn't match when it should. How is it that I can't concatenate a variable in the regex string?

Edit:

strval($integer) has solved my problem. I had to convert the integer value into a string before concatenating it (although I don't understand why):

$integer = 4;
if( preg_match( '/^([0-9]+,){0,' . strval($integer) . '}[0-9]+$/', $string ) ) { ... }
like image 578
Manolo Avatar asked Nov 30 '25 04:11

Manolo


1 Answers

Whenever concatenating a variable into a regex pattern, you should do so by passing the variable to the preg_quote function.

However, if the variable var is, like it is in your example 4, that won't make any difference. The pattern you're using will be:

/^([0-9]+,){0,4}[0-9]+$/

In which case, if it doesn't work: check the $string value, and make sure the pattern matches. BTW, /^(\d+,){,4}\d+$/ is shorter and does the same thing.

Calling strval doesn't solve anything, AFAIK... I've tested the code without strval, using the following snippet:

$string = '1234,32';
if (preg_match( '/^([0-9]+,){0,4}[0-9]+$/', $string) )
{
    echo 'matches',PHP_EOL;
    $count = 4;
    if (preg_match( '/^([0-9]+,){0,'.$count.'}[0-9]+$/', $string ) )
        echo 'matches, too',PHP_EOL;
}

The output was, as I expected:

matches
matches, too

In your case, I'd simply write:

$count = 4;
preg_match('/^(\d+,){,'.preg_quote($count, '/').'}\d+$/', $string);

This is undeniably safer than just calling strval, because you're not accounting for possible special regex chars (+[]{}/\$^?!:<=*. and the like)

like image 107
Elias Van Ootegem Avatar answered Dec 02 '25 19:12

Elias Van Ootegem



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!