在括号和单词PHP之间获取

时间:2021-07-07 21:42:08

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?

我想在大括号open和_hash}之间提取所有内容,我该如何实现呢?

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);
        }

1 个解决方案

#1


2  

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);

#1


2  

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);