如何对此字符串执行preg_match()


How to perform a preg_match() on this string?

我不擅长preg_match()。有人能帮我创建一个preg_match()来检索url中的最后一个参数吗。

PHP代码:

$url = "http://my.example.com/getThis";
$patern = ""; //need to create this
$result = preg_match($pattern, $url, $matches);

谢谢!

检索最后一个参数?另一种方法是使用preg_match,在/字符处拆分$url,然后获得最后一个元素。

$url = "http://my.example.com/getThis";
$arr = explode("/", $url);
$result = $arr[count($arr) - 1];

CCD_ 6将具有值CCD_。

Muhammad Abrar Istiadi和AD7six的答案是比这更好的方法,我强烈建议使用爆炸,

但要回答您的问题:

$url = "http://my.example.com/getThis";
$pattern = "/'/([^'/]*)$/";
preg_match($pattern, $url, $matches);
print_r($matches);`

在不需要正则表达式时(尤其是当它们不是你的专长时)不要使用

你只需要:

$lastSlash = strrpos($url, '/');
$result = substr($url, $lastSlash + 1);

有一个简单的PHP函数parse_url()来处理这个问题

这里有三种不同的方法,最后一种,使用parse_url()函数是最简单的。第一个是一个简单的正则表达式。

第二个是相同的正则表达式,但为生成的数组添加了键名。

第三种是使用PHP的parse_url()函数,该函数返回所有信息要简单得多,但确实捕获了路径的"/"。[path]=>/getThis

代码:

echo "Attempt 1:'n'n";
$url = "http://my.example.com/getThis";
$pattern = "/(.*?):'/'/(.*?)'/(.*)/"; //need to create this
$result = preg_match($pattern, $url, $matches);
print_r($matches);
echo "'n'nAttempt 2:'n'n";
$url = "http://my.example.com/getThis";
$pattern = "/(?<scheme>.*?):'/'/(?<host>.*?)'/(?<path>.*)/"; //need to create this
$result = preg_match($pattern, $url, $matches);
print_r($matches);
echo "'n'nAttempt 3:'n'n";
$better = parse_url($url);
print_r($better);

结果:

尝试1:

Array
(
    [0] => http://my.example.com/getThis
    [1] => http
    [2] => my.example.com
    [3] => getThis
)

Attempt 2:
Array
(
    [0] => http://my.example.com/getThis
    [scheme] => http
    [1] => http
    [host] => my.example.com
    [2] => my.example.com
    [path] => getThis
    [3] => getThis
)

Attempt 3:
Array
(
    [scheme] => http
    [host] => my.example.com
    [path] => /getThis
)

希望它能帮助^^