[英]preg_match is not working good in my condition
這是我的代碼,以獲取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 = 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';
工作正常。
這是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);
?>
在這里可以找到對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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.