Skip to content

variables with php regex

An answer to this question on Stack Overflow.

Question

I'm new around these parts, and I can usually find an answer to any issues I have using Google, but unfortunately I am stumped.

I am trying to complete a programming mission on a website I frequent. Essentially, what I have to do is take a list of scrambled words ,compare them to a list of unscrambled words and then post my words back the the web page. For an extremely simplified example, I'd have this word list:

linux
windows
mac

and these scrambled words:

ilxun
cma

so I'd need to post 'linux,mac'. Simple. However, I'm having trouble with my regex. I've written this simplified test code to try and get a working regex:

<?php
$subject = 'linux';
$pattern = 'nulix';
$length = strlen($subject);
if (preg_match("([$pattern]{"$length"})",$subject)) {
    echo True;
}
?>

My issue is in getting the length variable to work. I've all of the different variations that I found on this site. I've tried changing the quotes from double to single, I've tried double quotation on the outside and single on the inside and vice versa. I'm not really sure what to do. If I change the regex to:

if (preg_match("([$pattern]{5})",$subject))

it echos 1 exactly as I want it to, so I know that the regex is correct, I just can't work out how to make it use the $length variable. Any advice would be appreciated.

Answer

What you want is:

if (preg_match("([$pattern]{{$length}})",$subject)) {

The {$length} gets replaced by the number, so you need a second set of {} in order to retain the squiggly-brackets in the resulting string.

Also note that if you didn't need the brackets, you could write

"The length is $length"

and get out

"The length is 5"