【问题标题】:get variables from regular expresion从正则表达式中获取变量
【发布时间】:2019-03-16 06:42:43
【问题描述】:

我有以下字符串之一:

mystring
/mystring
mystring?test
/mystring?test

这是一个字符串,前面是一个可选的/,后面是一个可选的?test

我需要得到这个变量:

$string = "mystring"
$test = false / true depending if ?test is present

我正在尝试使用正则表达式,但在使用正确的模式时遇到了问题。我正在尝试:

\/?(\w+)(\??\w+)

例如,对于“mystring”,我得到这个:

Array
(
    [0] => /mystring
    [1] => mystrin
    [2] => g
)

这是一个示例代码:

<?
echo "<pre>";

$input = "/mystring";

$pattern = "/\/?(\w+)(\??\w+)/";

$matches = null;

preg_match($pattern, $input, $matches);

print_r($matches);
?>

【问题讨论】:

  • 你想要\/?\w+(?:\?\w+)?^\/?\w+(?:\?\w+)?$
  • 由于某种原因您是否被限制使用正则表达式?为什么不parse_url
  • @WiktorStribiżew 我没有得到具有该模式的两个变量
  • @Don'tPanic 我不限于正则表达式,我对其他方法持开放态度
  • 您是指群组吗?将它们添加到您想要的任何位置,例如\/?(\w+)(?:\?(\w+))?,见regex101.com/r/BtCw27/13v4l.org/Y2j6R

标签: php regex


【解决方案1】:

对于非正则表达式替代方案,如果您有兴趣,可以使用parse_url。它接受部分 URL,并且可以解析类似的字符串。

$components = parse_url($input);

$string 是删除了前导斜杠的路径,$test 是查询与字符串 'test' 的相等性。

$string = trim($components['path'], '/');
$test = isset($components['query']) && $components['query'] == 'test';

【讨论】:

    【解决方案2】:

    您将 ? 包含在 catch 表达式中。

    您应该使用的正则表达式:\/?(\w+)\??(\w+)?

    这将使用更少的步骤(46 与您的正则表达式的 56 相比),因此服务器上的负载也更少。

    演示:https://regex101.com/r/98QNeh/2

    【讨论】:

    • 您的正则表达式 also matches /mystring? 可能不是必需的。
    • 是的,您可以在我的答案中访问 regex101 链接并查看每一行的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    相关资源
    最近更新 更多