简体   繁体   English

preg_match在我的情况下无法正常工作

[英]preg_match is not working good in my condition

This is my code to get content between html tags. 这是我的代码,以获取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;
}

It return null. 它返回null。

if I write pattern like this 如果我写这样的模式

$pattern = '/<td valign\="top">(.*?)<\/td>/s';

It works fine. 工作正常。

This is html form to enter value of frm1 and to1. 这是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>

As Casimimir has already pointed out, use a Parser (eg SimpleXML ) instead. 正如Casimimir已经指出的那样,请改用解析器(例如SimpleXML )。
Consider the following code with two alternatives: 考虑以下代码,并提供两种选择:

<?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);
?>

A good introduction to SimpleXML can be found here . 这里可以找到对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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM