如何使preg_match数组数据在屏幕上有用


How to Make preg_match array data useful on Screen

我用preg_match()来检查来自XML提要的字符串(即:$resp = simplexml_load_file($API);)它返回了 1000 多个项目,并且preg_match我从存储在$matches中的每个项目中提取了一些数据,但我不知道如何使用preg_match存储在$matches中的内容

这是我所拥有的和我尝试过的。

注意:我有print_r($matches); 只是为了在修改预处理模式时可以看到结果。

    $matches;
        preg_match('/(?<='s|^)[a-zA-Z]{5,19} ?-?'d'd'd'd'd'd'd'd?*(?='s|$)/', $Apples, $matches);
            print_r($matches);
/*Note: $matches returns an array as such: Array ( [0] => Stringdata ) Array ( [0] => moreStringdata ) Array ( [0] => stillmoreStringData ) Array ( [0] => evenmoreStringData ) Array ( [0] => moreStringDataStill )... and I'm just wanting to use array[0] from each in the $results string which is output to the screen */  
    $results.= "<div class='MyClass'><a href='"$link'"><img src='"$linktopicture'"></a><a href='"$linktopageaboutapples'">$matches</a></div>";

我还尝试了$results字符串中的$matches(),$matches[]和$matches[0],但没有任何效果,由于我对使用数组不太了解,我想我会问,所以如果有人不介意让我直截了当可能是非常基本的,我将不胜感激,我提前感谢大家。

请务必阅读 preg_match 文档页面以了解函数的工作方式。

首先,检查preg_match是否返回1(这意味着$Apples中的值与模式匹配)或0(这意味着$Apples与模式不匹配)或FALSE(这意味着发生了错误)。

假设返回1,则 $matches[0] 将包含与模式匹配的$Apples字符串的整个部分。如果您有捕获组,则该匹配项中属于第一个捕获组的部分将在 $matches[1] 中找到,第二个捕获组位于 $matches[2] 中,依此类推。

如果您无法共享正则表达式模式,则无法查看您的模式是否包含任何捕获组,因此让我们使用此示例:

preg_match("/key:([A-Z]+);value:([0-9]+)/", "key:ERRORCODE;value:500", $matches);

现在$matches[0]应该包含"key:ERRORCODE;value:500",因为整个字符串都与模式匹配,$matches[1]应该包含"ERRORCODE",$matches[2]应该包含"500",因为这些部分符合完整模式的捕获组中的模式。