1

我正在尝试获取 URL 的一部分来创建嵌入代码。我有以下 URL 结构:

http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507

我需要使用preg_match将 URL 分成几部分。理想情况下,我想测试 URL 的结构并从 URL 中获取数值。最终,我想要一个以下形式的数组preg_match

Array (
    0 => 761507
    1 => 1518072
    2 => 761507
)

请注意,“foster-the-people”和“houdini”是动态元素,可以包含字母、数字和“-”,并且会从 URL 变为 URL。

谢谢您的帮助!

4

2 回答 2

2

试试这个:(更新)

http:\/\/www\.mtv\.com\/videos\/.*?\/([0-9]+)\/.*?id=([0-9]+)&vid=([0-9]+)

演示:

http://regexr.com?30qo4


代码 :

<?php
    $subject = "http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507";
    $pattern = '/http:\/\/www\.mtv\.com\/videos\/.*?\/([0-9]+)\/.*?id=([0-9]+)&vid=([0-9]+)/';
    preg_match($pattern, $subject, $matches);
    print_r($matches);

?>

输出 :

Array
(
    [0] => http://www.mtv.com/videos/foster-the-people/761507/houdini.jhtml#id=1518072&vid=761507
    [1] => 761507
    [2] => 1518072
    [3] => 761507
)

提示:您需要的元素$matches[1]$matches[2]$matches[3]

于 2012-05-01T20:06:23.550 回答
0

I would suggest you to use parse_url first to break your URL into individual components and then if needed use preg_match to get individual sub-items from $urlarr['query'] where $urlarr is return value of parse_url.

于 2012-05-01T20:15:10.347 回答