2

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.

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

5 Comments

Sweet, thanks mate! What do you mean it won't solve what I am trying to do though? When combined with nested foreach loops, it should work, right?
I take that part back, @dboxall123 - sorry! It is the case that both 'mac' and 'cam' will match the scramble 'mca'. In this context, that's okay, though. And you're limiting things by length so you won't accidentally match 'macc'.
If this answer was helpful to you, feel free to press the up arrow by it, or hit the big check mark next to it if it's the best answer to your question.
Thanks for the help and the explanation Richard, much appreciated. Tomorrow I can finish my code and the 500 points will be mine! :)
There is no red check though, I think that I need reputation for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.