Php Preg match未找到正确的字符串
我有一个问题,我有一个脚本,它应该搜索XML文件中匹配的字符串。 这是我的剧本:Php Preg match未找到正确的字符串,php,xml,regex,Php,Xml,Regex,我有一个问题,我有一个脚本,它应该搜索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), $
<?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>
OR-1361163557-gr
1361163557
OGPDX-2.01.01
问题是当我preg匹配'product'时,它工作正常,但当我尝试preg匹配另一个字符串,即'message'时,它不工作
我对解决方案很好奇,提前谢谢 你能检查一下这个代码吗,我注意到你把
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 />";
}
}
?>
问题在于您的逻辑:您只检查了$line
的最后一个值,它包含
那么您在搜索什么呢?一行xml…
搜索“产品”(在最后一行)时,$行在最后一行
foreach ($lines as $line_num => $line)
{
if (preg_match("/message/", $line , $found))
{
echo "Line: $line_num - ".$found[0]." <br>";
}
}
foreach($line作为$line\u num=>$line)
{
if(preg_match(“/message/”,$line,$found))
{
echo“Line:$Line_num-”$found[0]。“
”;
}
}
你说的“不起作用”是什么意思?它不是找到了你期待的所有匹配项吗?它是否匹配了您不希望它匹配的内容?它没有找到我期望的所有匹配项哪一个没有找到?它确实找到了“产品”,但没有找到您可以用来遍历XML的任何其他内容。