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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler