尝试进行网页抓取,但无法理解php如何分析html标记。我目前不在我的网络服务器上,所以我在线测试代码。 在http://phptester.net/,我的代码是:
<?php
$start = "<title>";
$end = "</title>";
$data = "<title>this is a test </title>";
echo $start . " " . $end . " " . "<br>";
echo $data . "<br>";
echo strlen($start) . "<br>";
echo htmlspecialchars($data) . "<br>";
$data = stristr(htmlspecialchars($data), htmlspecialchars($start));
$data = substr(htmlspecialchars($data), strlen($start));
if($data===false){
echo 'string not found';
}
else{
echo $data;
}
现在有一些样本输入和输出。
Input
$start="<title>"
$end="</title>"
Output
(blank line)
(blank line)
7
<title>this is a test </title>
;title>this is a test </title>
Input
$start=<title>
$end=</title>
Output
<title> </title>
(blank line)
13
<title>this is a test </title>
string not found
更改
$data = stristr(htmlspecialchars($data), htmlspecialchars($start));
到
$data = stristr(htmlspecialchars($data), $start);
并重新测试。
Input
$start="<title>"
$end="</title>"
Output
(blank line)
(blank line)
7
<title>this is a test </title>
string not found
Input
$start="<title>"
$end="</title>"
Output
<title> </title>
(blank line)
13
<title>this is a test </title>
>this is a test </title>
我期待最后一个工作。我认为它将在一个实际的Web服务器上,因为看起来这个在线php测试器在字符串的开头插入了额外的4个字符,这使得最后四个字符被删除。
我接下来尝试了http://sandbox.onlinephpfunctions.com/,没有任何htmlspecialchar函数的原始字符串完全符合我的预期。我在两个版本中都使用了相同的版本。现在我很困惑。
对不起,很长的帖子。如果有人可以向我解释php如何解析HTML标签,我会非常感激。谢谢。
答案 0 :(得分:0)
这不是PHP解析因此导致的混乱。你只是看着字符串操作。
因此,为我主机上的输出提供更多上下文代码
$start = "<title>";
$end = "</title>";
$data = "<title>this is a test </title>";
echo "Showing Start: " . $start . " " . $end . " " . "<br>";
echo "Showing Data: " . $data . "<br>";
echo "Showing LEN Start: " . strlen($start) . "<br>";
echo "Showing Data special: " . htmlspecialchars($data) . "<br>";
$data = stristr(htmlspecialchars($data), htmlspecialchars($start));
echo "Showing Data stristr: " . $data . "<br>";
$data2 = stristr(htmlspecialchars($data), $start);
echo "Showing Data2 stristr: " . $data2 . "<br>";
$data = substr(htmlspecialchars($data), strlen($start));
if($data===false){
echo 'string not found';
}
else{
echo "Showing Data substr: " . $data . "<br>";
}
将提供以下输出:
Showing Start:
Showing Data:
Showing LEN Start: 7
Showing Data special: <title>this is a test </title>
Showing Data stristr: <title>this is a test </title>
Showing Data2 stristr:
Showing Data substr: ;title>this is a test </title>
上述每一行的说明。
fyi你的if永远不会是假的,除非你没有字符串或你没有索引的起点,即70.
答案 1 :(得分:0)
你的代码显然有错误。您正在使用多个$data
操作重写=
变量。相反,使用这样的东西:
.........
$data = "<title>this is a test </title>";
.........
$data1 = stristr(htmlspecialchars($data), htmlspecialchars($start));
$data2 = substr(htmlspecialchars($data), strlen($start));
.........
if (!$data1 && !$data2){
echo 'not found';
}
......