PHP:未定义的偏移量:3 - preg_match_all

时间:2016-04-24 23:21:50

标签: php regex url

我有来自示例的网址结构:

http://www.example.com/directory/some-text-a1-vs-sec-text-b2-vs-third-text-vs-last-text-c1/

我的正则表达式是:

preg_match_all("/([^\/.]+?)(?:-vs-|\.\w+$)/", $html, $matches);

预期结果:

some-text-a1
sec-text-b2
third-text
last-text-c1

结果我得到了:

some-text-a1
sec-text-b2
third-text
Notice: Undefined offset: 3 in F:\xampp\htdocs\url.php on line 41

完整代码:

$html = "http://www.example.com/directory/some-text-a1-vs-sec-text-b2-vs-third-text-vs-last-text-c1/";
preg_match_all("/([^\/.]+?)(?:-vs-|\.\w+$)/", $html, $matches);

$prvi = "some-text-a1";
$drugi = "sec-text-b2";
$treci = "third-text";
$cetvrti = "last-text-c1";

echo "URL: ".$html."<br>";

if($prvi == $matches[1][0]){echo "1st O.K. - ".$prvi." = ".$matches[1][0]."<br>";}
if($drugi == $matches[1][1]){echo "2nd O.K. - ".$drugi." = ".$matches[1][1]."<br>";}
if($treci == $matches[1][2]){echo "3rd O.K. - ".$treci." = ".$matches[1][2]."<br>";}
if($cetvrti == $matches[1][3]){echo "4th O.K. - ".$cetvrti." = ".$matches[1][3]."<br>";}

想法我错过了什么?我想结束斜杠/是我的正则表达式中的问题。

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

这是一种不同的方法 - 使用 parse_url 爆炸功能。

<?php
$url = 'http://www.example.com/directory/some-text-a1-vs-sec-text-b2-vs-third-text-vs-last-text-c1/';

$parsedUrl = parse_url($url);

var_dump($parsedUrl);

$path = explode('/',trim($parsedUrl['path'],'/'));

var_dump($path);

if (is_array($path) && $path[0] === 'directory') {
        if (isset($path[1])) {
                $vs = explode('-vs-',$path[1]);
                var_dump($vs);
        }
}

答案 1 :(得分:1)

试试这个

(?<=vs-)(.*?)(?=-vs)|(?<=\/)([^\/]*?)(?=-vs)|(?<=vs-)(.*?)(?=\/|$)

Regex demo

<强>解释
(?<=…):正面观察sample
( … ):捕获小组sample
.:除了换行符sample之外的任何字符 *:零次或多次sample
?:一次或无sample
(?=…):积极前瞻sample
|:替代/或操作数sample
\:逃脱一个特殊字符sample
[^x]:一个不是x sample的字符 $:字符串结束或行尾,具体取决于多行模式sample

PHP:

<?php
$re = "/(?<=vs-)(.*?)(?=-vs)|(?<=\\/)([^\\/]*?)(?=-vs)|(?<=vs-)(.*?)(?=\\/|$)/"$
$str = "http://www.example.com/directory/some-text-a1-vs-sec-text-b2-vs-third-t$

preg_match_all($re, $str, $matches);
print_r($matches[0]);

输出:

Array
(
    [0] => some-text-a1
    [1] => sec-text-b2
    [2] => third-text
    [3] => last-text-c1
)