【发布时间】: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/1和3v4l.org/Y2j6R