dongmeiran609914 2016-04-24 23:21
浏览 76
已采纳

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

I have URL structure from example:

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

My Regex is:

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

Expected result:

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

Result I got:

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

Full code:

$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>";}

Ideas what am I missing? I suppose the ending slash / is the problem within my regex.

Any ideas? Thanks!

  • 写回答

2条回答 默认 最新

  • douxi7219 2016-04-25 01:56
    关注

    Try this

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

    Regex demo

    Explanation:
    (?<=…): Positive lookbehind sample
    ( … ): Capturing group sample
    .: Any character except line break sample
    *: Zero or more times sample
    ?: Once or none sample
    (?=…): Positive lookahead sample
    |: Alternation / OR operand sample
    \: Escapes a special character sample
    [^x]: One character that is not x sample
    $: End of string or end of line depending on multiline mode 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]);
    

    Output:

    Array
    (
        [0] => some-text-a1
        [1] => sec-text-b2
        [2] => third-text
        [3] => last-text-c1
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 maccms影视模板 制作影视网站失败 求
  • ¥15 stm32按键设置闹钟数进退位不正常
  • ¥15 自己写的测试驱动程序无法启动
  • ¥15 三电平逆变器中点电位平衡问题
  • ¥20 这怎么写啊 java课设
  • ¥15 用C语言完成一个复杂的游戏
  • ¥15 如何批量更改很多个文件夹里的文件名中包含文件夹名?
  • ¥50 MTK手机模拟HID鼠标出现卡顿
  • ¥20 求下下面这个数据结构代码