0

I have two variables as follows:

$string1 = '/test/10/25';
$string2 = '/test/[0-9]+/[0-9]+

Is it possible to make PHP compare these two strings and push the actual ID's (10 and 25) into an array like so by using the regex as some sort of guidance?

Array
(
    [0] => 10
    [1] => 25
)

I tried playing around with preg_match() but this just puts everything into the same array key.

1 Answer 1

1

This will work for you

<?php

$string1 = '/test/10/25';
$string2 = '/\/test\/([0-9]+)\/([0-9]+)/';
$matches = [];
preg_match($string2, $string1, $matches);

$array = [];

for($i = 1; $i < count($matches); $i ++)
{
    array_push($array, $matches[$i]);
}

print_r($array);

$array will have the matches inside. I had to change the regex string because it was not "valid" for php.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, exactly what I was looking for. Thanks for the help! :)

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.