Manolo
Manolo

Reputation: 26370

Concatenate variables in a regular expression string with preg_match()

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 ) ) { ... }

Upvotes: 3

Views: 4530

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

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)

Upvotes: 3

Related Questions