TaylorOtwell
TaylorOtwell

Reputation: 7337

Preg_grep to find request URI in array of possibilities

I have an array that contains possible request URIs. Some of the array values could contain comma delimited URIs:

array(
     0 => 'GET /, GET /something',
     1 => 'GET /login',
     2 => 'GET /user/profile',
)

Let's say I want to find the key that contains "GET /something". How can I use preg_grep to do this? Currently, I'm trying this:

preg_grep('/(.*)GET \\'.$uri.'(.*)/', $array);

However, I just get an empty array back. Any idea what I'm doing wrong?

Upvotes: 1

Views: 250

Answers (4)

Qtax
Qtax

Reputation: 33918

I don't have PHP to test this, but according to the docs something simple like this could work:

array_keys(preg_grep('!\bGET /something\b!', $array));

Upvotes: 0

The Mask
The Mask

Reputation: 17427

try this: $arr = array('GET /, GET /something','GET /login', 'GET /user/profile');

preg_match("/GET\s*\/([^\n]+)/", join("\n", $arr), $matched); 
print_r($matched);

Upvotes: 0

NorthGuard
NorthGuard

Reputation: 963

Rather than having $uri in your string for preg_grep, concat it into a $pattern var first (for ease of reading mostly plus you can echo it and check as the above comment suggested):

$uri = 'something';
$pattern = '/(.*)GET \/'.$uri.'(.*)/';
$array = preg_grep($pattern, $starting_array);
print_r($array);

As to answer your question specifically, you escaped the wrong type of slash :p

Upvotes: 2

brian_d
brian_d

Reputation: 11395

Try

  $array = array(
     0 => 'GET /, GET /something',
     1 => 'GET /login',
     2 => 'GET /user/profile',
  );

 $uri = 'something';
 $matches = preg_grep('{(.*)GET /'.$uri.'(.*)}', $array);
 var_dump(array_search($matches[0], $array));

Upvotes: 1

Related Questions