[英]what's the easiest way to parse a PHP string like this
我嘗試使用PHP解析字符串以提取信息,部分內容如下所示
<div>All Versions:</div>
<div class='rating' role='img' tabindex='-1' aria-label='5 stars, 193984 Ratings'><div>
PHP獲取這兩個數字的最簡單方法是什么?
(1)星數-5
(2)評分-193984
PS請不要將其視為HTML解析,而是一個字符串
XML解析器愛好者會建議您使用解析器從div中獲取屬性。
$xml = new XMLReader(); //Setup parser
$xml->XML("<div>All Versions:</div><div class='rating' role='img' tabindex='-1' aria-label='5 stars, 193984 Ratings'></div>");
$xml->read();
while($xml->read()) { //Run through each node
if($xml->getAttribute('class') == 'rating') { //Look for class of 'rating'
// Break apart aria-label
list($stars, $ratings) = explode(', ', $xml->getAttribute('aria-label'));
$stars = intval($stars); //Grab the integer part of the strings
$ratings = intval($ratings);
break;
}
}
$xml->close();
但是,這取決於您要如何識別div。 如果您還想包含其他標識符(例如ID等更具體的標識符),則可以將它們包括在if語句中。
一旦隔離了頁面的這一部分(無論是否進行DOM分析),就可以使用以下方法輕松提取兩個數字:
preg_match('#(\d+) stars, (\d+) Ratings#i', $source, $match);
list(, $stars, $ratings) = $match;
請注意,它適用於您的示例。 如果在其他情況下還存在其他人類可讀屬性,或以其他方式排序,則您需要將字符串以逗號分隔,然后分別在每個部分中搜索星號或等級。
$string="<div class='rating' role='img' tabindex='-1' aria-label='5 stars, 193984 Ratings'><div>"
$pattern = '/aria-label=\'(\d+) stars, (\d+) Ratings\'/';
preg_match($pattern, $string, $matches);
echo "<pre>";
print_r($matches);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.