【问题标题】:How to Make preg_match array data useful on Screen如何使 preg_match 数组数据在屏幕上有用
【发布时间】:2013-11-09 19:30:20
【问题描述】:

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

这是我所拥有的以及我尝试过的。

注意:我有 print_r($matches);只是这样我可以在修改 preg 模式时看到结果。

    $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],但没有任何效果,因为我对使用数组不太了解,所以我想我会问是否有人愿意'不介意让我直接了解可能非常初级的东西,我会非常感激,我提前感谢大家。

【问题讨论】:

  • 还有$matches的内容是什么?
  • 请在您的代码示例中添加 $Pattern 的定义(并更正错字)并将 print_r($matches) 的输出添加到问题中。
  • @Arkanon 为什么有人需要 Pattern 的定义? (除了我的竞争对手)我只需要知道如何使用存储在 $matches 中的数据。
  • @Arkanon 错字已更正并添加了 $matches 示例

标签: php regex arrays


【解决方案1】:

请务必阅读preg_match doc page 以了解该功能的工作方式。

首先,检查 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”,因为这些部分适合完整模式的捕获组中的模式。

【讨论】:

  • 您好@Arkanon,我已经阅读了您提供的 preg_match 文档(在您提供之前),但我仍然不明白很多。很抱歉没有分享我的模式。我将编辑我的初始问题以使用与我正在提取的内容相似的模式,但是,我不知道:“key:ERRORCODE;value:500” 请稍等片刻来更新我的初始问题。
  • 我更新了模式和数组数据样本。我认为 Array ( [0] => data ) Array ( [0] => moredata )...等就足够了。我的缺点是不够清楚
  • 当然,存储在 $matches 中的数据不仅可以用于通过 print_r() 查看吗?????? (我希望)因为我使用 preg_match 从要注入 $results 字符串的字符串中提取小位
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2011-08-17
  • 2016-12-05
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多