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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?