【问题标题】:PHP regex preg_match separate variables in urlPHP regex preg_match url中的单独变量
【发布时间】:2017-07-14 23:30:29
【问题描述】:

我有字符串

$string = 'foo/{id}/bar/{name}';

我正在尝试进行正则表达式过滤

想要的输出:

$matches = [
  0 => 'foo/{id}/bar/{name}',
  1 => 'id',
  2 => 'name'
]

到目前为止:(正则表达式是我的弱点)

preg_match('~^' . $magic . '$~', $string, $matches)

编辑:url中有*n个{variable}

【问题讨论】:

  • 你为什么不用explode()呢?
  • 刀就够了,为什么还要用电锯?使用explode()
  • {id}{name} 是占位符还是文字?也许3v4l.org/eo0kO? (取决于“名称”的定义)
  • @chris85 {id}{name} 是文字
  • 不是答案,但这个regex101.com 对于调试正则表达式非常有用

标签: php regex preg-match


【解决方案1】:

使用以下preg_match_all 方法:

$str = 'foo/{id}/bar/{name}/many/{number}/of/{variables}';
preg_match_all('/\{([^{}]+)\}/', $str, $m);

print_r($m[1]);

输出:

Array
(
    [0] => id
    [1] => name
    [2] => number
    [3] => variables
)

【讨论】:

  • 我可以使用它吗:$str = 'foo/{id}/bar/{name}/many/{number}/of/{variables}';
  • 甚至 $str = 'foo/{$id}';`
  • 您想只提取所有用{} 括起来的值吗?喜欢Array ( [0] => {id} [1] => {name} [2] => {number} [3] => {variables} )
  • 是的,所有带有{ }的值,但是array[0]应该是整个url
【解决方案2】:

可以使用regex 完成,但也可以使用简单的字符串和数组处理来完成:

$string = 'foo/{id}/bar/{name}';

// Collect the values here, indexed by parameter names
$params = array();
// Remove any trailing and ending separator then split to pieces
$pieces = explode('/', trim($string, '/'));
// Every two pieces, the first one is the key, the other is the value
foreach (array_chunk($pieces, 2) as list($key, $value)) {
    // Put the values in $params, index by keys
    $params[$key] = $value;
}

print_r($params);

它输出:

Array
(
    [foo] => {id}
    [bar] => {name}
)

list($key, $value) 结构从 PHP 5.5 开始工作。如果你被旧版本卡住了,你可以用旧的、更冗长的方式来做:

foreach (array_chunk($pieces, 2) as $pair) {
    list($key, $value) = $pair;
    $params[$key] = $value;
}

【讨论】:

    【解决方案3】:

    我在 cmets 中看到 Romans 的回答是,这不仅仅是他需要的两个变量。通过滚动搜索更多变量来更新我的回复

    这也可以通过 strpos 和 strrpos 来完成。

    $string = "foo/{id}/bar/{name}/many/{number}/of/{variables}";
    $pos = strpos($string, "{"); // find the first variable 
    $matches = array();
    while($pos!=0){ // while there are more variables keep going
        $matches[] = substr($string, $pos+1, strpos($string, "}", $pos)-$pos-1); //substring the variable from $pos -> ending }
        $pos = strpos($string, "{", $pos+1); // find the next variable
    }
    var_dump($matches);
    

    strpos 找到“/”的位置并加一(这样子字符串中就不会包含“/”)。
    http://php.net/manual/en/function.strpos.php

    https://3v4l.org/pWXTh

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多