我有以下字符串:
... 12:32 +0304] "GET /test.php?param=value ....
我想从这个字符串中提取test.php。我试着找到一个php函数来做这件事,但没有任何帮助。所以我的下一个猜测是,regex怎么样?我花了这么长时间试图获得get/和之间的部分?。我失败得很惨。。。
php中是否存在可以帮助我的函数,或者我是否需要regex?如果我这样做,我如何从一根绳子中得到一根绳子?重要的是,我不想知道字符串中是否有test.php。我想在获取/和?之间获取所有信息?。
正则表达式提取捕获组中GET /
和?
之间的任何内容:
GET '/(.*?)'?
演示:https://regex101.com/r/wR9yM5/1
在PHP中,它可以这样使用:
$str = '... 12:32 +0304] "GET /test.php?param=value ....';
preg_match('/GET '/(.*?)'?/', $str, $re);
print_r($re[1]);
演示:https://ideone.com/0XzZwo
<?php
$string = '... 12:32 +0304] "GET /test.php?param=value ....';
$find = explode("GET /", explode(".php", $string)[0])[1].".php";
echo $find; // test.php
?>
试试这个:
(?>('/))('w+.php)
或者,如果你想要任何分机号,2或3位数字:
(?>('/))('w+.'w{3})
如果只有3,则删除括号中的"2"。
PHP代码:
<?php
$subject='12:32 +0304] "GET /test.php?param=value';
$pattern='/(?>('/))('w+.{2,3})/s';
if (preg_match($pattern, $subject, $match))
echo $match[0];
?>
不带正则表达式:
function between_solidus_and_question_mark($str) {
$start = strtok($str, '/');
$middle = strtok('?');
$end = strtok(null);
if($start && $end) {
return $middle;
}
}
$str = '... 12:32 +0304] "GET /test.php?param=value ....';
var_dump(between_solidus_and_question_mark($str));
输出:
test.php