Explode() 字符串将数组分成太多元素

Explode() String Breaking Array Into Too Many Elements

我正在努力抓取然后解析 HTML 字符串以获取 href 中的两个 URL 参数。在抓取我需要的元素 $description 之后,准备解析的完整字符串是:

<a target="_blank" href="CoverSheet.aspx?ItemID=18833&amp;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>"

所以我不明白为什么在用双引号分隔符爆炸后回显时,它一次只打印一个数字..

有一个非常简单的方法:

你的力量:

$str ='<a target="_blank" href="CoverSheet.aspx?ItemID=18833&amp;MeetingID=773">Description</a><br>';

创建子字符串:

$params = substr( $str, strpos( $str, 'ItemID'), strpos( $str, '">') - strpos( $str, 'ItemID') );

你会得到这样的 substr :

ItemID=18833&MeetingID=773

现在想做什么就做什么!

您得到错误响应的原因是您使用了错误的变量。

$htarray = explode('"', $meetingID);

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

echo "Meeting ID is " . $htarray[0] ; // this prints 773

不过有一种更简单的方法可以做到这一点,那就是使用正则表达式:

$description = '<a target="_blank" href="CoverSheet.aspx?ItemID=18833&amp;MeetingID=773">Description</a><br>';

$meetingID = "Not found";
if (preg_match('/MeetingID=([0-9]+)/', $description, $matches)) {
    $meetingID = $matches[1];
}

echo "Meeting ID is " . $meetingID;
// this prints 773 or Not found if $description does not contain a (numeric) MeetingID value