【问题标题】:Preg match does not find the correct stringPreg 匹配未找到正确的字符串
【发布时间】:2013-03-21 08:05:26
【问题描述】:

我有一个问题,我有一个脚本应该在 XML 文件中搜索匹配的字符串。 这是我的脚本:

   <?php
$file = "klein.xml";
$lines = file($file);
foreach ($lines as $line_num => $line)
{
    echo htmlentities($line);
    echo "<br>";

}

   if (preg_match("/message/", htmlentities($line), $found))
   {
     echo "Found!";
     echo $found[0]; 
     echo "test";
   }
   else
   {
       echo "Not Found!";
   }
?>

这是我正在使用的 xml 文件:

    <?xml version="1.0" encoding="ISO-8859-1"?>
<product-data>
<message-header>
<message-id>OR-1361163557-gr</message-id>
<message-timestamp>1361163557</message-timestamp>
<export-version current_version="1">OGPDX-2.01.01</export-version>
</message-header>
</product-data>

问题是当我预匹配“产品”时它可以正常工作,但是当我尝试预匹配另一个字符串时,即“消息”它不起作用?

我很好奇解决方案,在此先感谢!

【问题讨论】:

  • “不起作用”是什么意思?它没有找到您期望的所有匹配项吗?它与您不想要的东西匹配吗?
  • 它没有找到我期望的所有匹配项
  • 哪个没有找到?
  • 它确实找到了“产品”,但没有找到其他任何东西
  • 可以使用DOMDocument来遍历XML。

标签: php xml regex


【解决方案1】:

你能检查一下这段代码吗,我注意到你把if循环放在foreach之外;因此只执行最后一行。

<?php
$file = "klein.xml";
$lines = file($file);
foreach ($lines as $line_num => $line)
{
   if (preg_match("/message/", htmlentities($line), $found))
   {
     echo "Found ".$found[0]."<br />";
   }
}
?>

【讨论】:

    【解决方案2】:

    问题在于你的逻辑:你只检查 $line 的最后一个值,它包含 &lt;/product-data&gt;

    【讨论】:

      【解决方案3】:

      那么你在搜索什么?一行你的 xml ...
      当您搜索“产品”(在最后一行)时,$line 在最后一行。

      foreach ($lines as $line_num => $line)
      {
         if (preg_match("/message/", $line , $found))
         {
           echo "Line: $line_num - ".$found[0]." <br>";
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多