在字符串中查找单词/字符串,我需要正则表达式吗?

时间:2016-08-03 12:20:32

标签: php regex string parsing extract

我得到了以下字符串:

... 12:32 +0304] "GET /test.php?param=value ....

我想从此String中提取 test.php 。我试图找到一个可以做到这一点的PHP功能,但没有任何帮助。所以我的下一个猜测是,正则表达式怎么样,我试了很久才得到GET /和?之间的部分。我失败了......在PHP中存在一个功能可以帮助我或者我需要正则表达式吗?如果我这样做,我如何从字符串中获取字符串?重要的是,我不想知道test.php是否在字符串中。我希望得到GET /和之间的所有内容。

非常感谢

4 个答案:

答案 0 :(得分:2)

<?php
    $string     =   '... 12:32 +0304] "GET /test.php?param=value ....';
    $find       =   explode("GET /", explode(".php", $string)[0])[1].".php";
    echo $find; // test.php
?>

答案 1 :(得分:2)

正则表达式在捕获组中的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

答案 2 :(得分:0)

试试这个:

(?>(\/))(\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];
?>

答案 3 :(得分:0)

没有正则表达式:

select brand, type, 
max(case when customer_type='Adult' then cost end) as Adult,
max(case when customer_type='Senior Citizen' then cost end) as Senior Citizen,
max(case when customer_type='Student' then cost end) as Student
from table
Group by brand, type

输出:

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