Php preg_match在我的状态下不太好
这是我在html标记之间获取内容的代码Php preg_match在我的状态下不太好,php,regex,Php,Regex,这是我在html标记之间获取内容的代码 $stringtext=file_get_contents($url); $frm1=htmlspecialchars($_REQUEST['from1']); $to1=htmlspecialchars($_REQUEST['to1']); $dt= find_between($newstr,$frm1,$to1); function find_between($string, $start, $end, $trim = true, $greedy
$stringtext=file_get_contents($url);
$frm1=htmlspecialchars($_REQUEST['from1']);
$to1=htmlspecialchars($_REQUEST['to1']);
$dt= find_between($newstr,$frm1,$to1);
function find_between($string, $start, $end, $trim = true, $greedy = false) {
$pattern = '/'.preg_quote($start,'\"').'(.*';
if (!$greedy) $pattern .= '?';
$pattern .= ')'.preg_quote($end,'/').'/s';
preg_match($pattern, $string, $matches);
$string = $matches[0];
if ($trim) {
$string = substr($string, strlen($start));
$string = substr($string, 0,-strlen($end));
}
return $string;
}
它返回null
如果我这样写模式
$pattern = '/<td valign\="top">(.*?)<\/td>/s';
$pattern='/(.*?)/s';
它很好用
这是一个html表单,用于输入frm1和to1的值
<form action="" method="post" id="frm1" style="display:none">
<table>
<tr>
<td>From: <input type="text" name="from1" /></td>
<td>To: <input type="text" name="to1" /></td>
</tr>
</table></form>
发件人:
致:
正如Casimimir已经指出的那样,使用解析器(例如SimpleXML
)
考虑下面的代码有两种选择:
<?php
$html = '
<form action="" method="post" id="frm1" style="display:none">
<table>
<tr>
<td>From: <input type="text" name="from1" /></td>
<td>To: <input type="text" name="to1" /></td>
</tr>
</table></form>
';
$xml = simplexml_load_string($html);
# traverse the DOM directly
$input_version1 = $xml->table->tr->td->input;
# use an xpath query to get the same element
$input_version2 = $xml->xpath("//form//input[@name='from1']")[0];
print_r($input_version1);
print_r($input_version2);
?>
table->tr->td->input;
#使用xpath查询获取相同的元素
$input_version2=$xml->xpath(//form//input[@name='from1'])[0];
打印(输入版本1);
打印(输入版本2);
?>
您可以找到有关
SimpleXML
的详细介绍。使用DOMDocument,而不是直接字符串方法。@casimire我比较新鲜。请解释如何使用DomainCumentYou必须找到一个教程,因为它不在SO的范围内,而且太长,无法解释。简而言之,DOMDocument使用XML或html文档构建一个树。然后您可以更轻松地(无错误地)查询或编辑它。让它打印$pattern
以调试代码。SimpleXML是为XML而不是html设计的。例如,它将在所有未关闭的标记上失败,如
,
。。。如果/>
(自动关闭标记)丢失,或者没有根元素。如果源代码的xml语法有一点错误,simplexml\u load…
将失败,因为html是非常允许的。。。(作为旁白,simplexml一点也不简单)。
function find_between($string, $start, $end, $trim = true, $greedy = false) {
$start=htmlspecialchars_decode($start);
$end=htmlspecialchars_decode($end);
$pattern = '/'.preg_quote($start,'\"').'(.*';
if (!$greedy) $pattern .= '?';
$pattern .= ')'.preg_quote($end,'/').'/s';
preg_match($pattern, $string, $matches);
$string = $matches[0];
if ($trim) {
$string = substr($string, strlen($start));
$string = substr($string, 0,-strlen($end));
}
return $string;
}