【发布时间】:2021-01-13 10:40:03
【问题描述】:
我正在抓取并解析 HTML 字符串以获取 href 中的两个 URL 参数。抓取我需要的元素 $description 后,准备解析的完整字符串是:
<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>
下面我使用explode参数根据=分隔符拆分$description变量字符串。然后我根据双引号分隔符进一步展开。
我需要解决的问题:我只想在双引号“773”之前打印 MeetingID 参数的数字。
<?php
echo "Description is: " . htmlentities($description); // prints the string referenced above
$htarray = explode('=', $description); // explode the $description string which includes the link. ... then, find out where the MeetingID is located
echo $htarray[4] . "<br>"; // this will print the string which includes the meeting ID: "773">Description</a><br>"
$meetingID = $htarray[4];
echo "Meeting ID is " . substr($meetingID,0,3);
?>
上面使用 substr 的 echo 语句可以打印会议 ID 773。
但是,我想在 MeetingID 参数超过 999 的情况下做到这一点,那么我们需要 4 个字符。所以这就是为什么我想用双引号来分隔它,所以它会打印双引号之前的所有数字。
我尝试在下面隔离双引号之前的所有金额...但它似乎还没有正常工作。
<?php
$htarray = explode('"', $meetingID); // split the $meetingID string based on the " delimiter
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
?>
问题,为什么数组 $meetingID[0] 不打印分隔符之前的三个数字,“,而是只打印一个数字?如果explode函数正常工作,它不应该拆分上面引用的字符串基于双引号,只有两个元素?字符串是
"773">Description</a><br>"
所以我不明白为什么在使用双引号分隔符爆炸后回显时,一次只打印一个数字..
【问题讨论】:
-
“为什么数组 $meetingID[0] 不打印分隔符前的三个数字”——因为
$meetingID是字符串。分解后的数组是$htarray。我想你在找$htarray[0]? -
你是对的!谢谢,问题解决了。
-
如果你能把它写成答案,我可以给你正确的答复。
-
您通常最好使用 DOMDocument 之类的东西处理 HTML,请参阅 stackoverflow.com/questions/3577641/…。
-
@NigelRen 感谢我正在使用 PHP 简单 Dom 解析器,但是一旦我有了字符串,就会尝试变得更高级。