Donny van V
Donny van V

Reputation: 981

Get between brackets and word PHP

Im trying to extract a specific value from multiple strings. Lets say i have the following strings:

/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}

I want to extract all between curly bracket open and _hash}, how can i achieve this?

The output should be a array:

    $array = [
        'some_hash', 
        'user_hash',
        'date_hash',
        'user_hash'
    ];

Current code:

 $matches = [];
        foreach (\Route::getRoutes()->getRoutes() as $route) {
            $url = $route->getUri();
            preg_match_all('/({.*?_hash})/', $url, $matches);
        }

Upvotes: 2

Views: 333

Answers (1)

Dekel
Dekel

Reputation: 62616

You can use regex for that:

$s = '/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}';

preg_match_all('/{(.*?_hash)}/', $s, $m);
var_dump($m[1]);

The output will be:

array(4) {
  [0]=>
  string(9) "some_hash"
  [1]=>
  string(9) "user_hash"
  [2]=>
  string(9) "date_hash"
  [3]=>
  string(9) "user_hash"
}

Based on your edit you probably want:

$all_matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
    $url = $route->getUri();
    preg_match_all('/{(.*?_hash)}/', $url, $matches);
    $all_matches = array_merge($all_matches, $matches[1]);
}
var_dump($all_matches);

Upvotes: 2

Related Questions