PHP preg_match 即使存在正则表达式模式也会失败

PHP preg_match fails even though regex pattern is present

我想重现这个面包屑数组,其中每个面包屑减去面包屑的最后一项。

我试过的。我已经尝试 preg_matching 模式“/.*(?=\s»\s)/”,它应该抓取 » 最后一个实例之前的所有内容。这是我尝试的解决方案:

<?php
$breadcrumb = array (
  'More » Brackets & Mounting » StarTech MNRISERCLMP',
  'Printer Consumables » Toner Cartridges » Other Brand » Sharp MX27GTMA',
  'More » Audio Visual » TVs » Philips 43BDL4051T-EXG',
  'Servers » Server Cables & Accessories » Other Server Accessories » LINKBASIC LB-WCC09-655-CA'
);



foreach($breadcrumb as $breadcrumbs){
        preg_match("/.*(?=\s»\s)/",$breadcrumbs,$matches);
        echo $matches[1] . '<br />';
    }

给出:


Warning: Undefined array key 1 in [...][...] on line 13


Warning: Undefined array key 1 in [...][...] on line 13


Warning: Undefined array key 1 in [...][...] on line 13


Warning: Undefined array key 1 in [...][...] on line 13

我知道错误告诉我没有匹配项,但从逻辑上讲我看不出 preg_match 失败的原因。

实际上你的结果会在 $matches[0]:

echo $matches[0] . '<br />';

或者试试这个模式:

preg_match("/(.+)\s»\s.+$/", $breadcrumbs, $matches);
echo $matches[1] . '<br />';