2 回答

TA貢獻1773條經驗 獲得超3個贊
不要使用正則表達式來解析 HTML。
您有一個簡單的目標:將文本內容限制為給定的字數,確保 HTML 保持有效。
為此,我建議循環遍歷文本節點,直到您計算出一定數量的單詞,然后刪除之后的所有內容。
$dom = new DOMDocument();
$dom->loadHTML($post_content);
$xpath = new DOMXPath($dom);
$all_text_nodes = $xpath->query("//text()");
$words_left = 48;
foreach( $all_text_nodes as $text_node) {
$text = $text_node->textContent;
$words = explode(" ", $text); // TODO: maybe preg_split on /\s/ to support more whitespace types
$word_count = count($words);
if( $word_count < $words_left) {
$words_left -= $word_count;
continue;
}
// reached the threshold
$words_that_fit = implode(" ", array_slice($words, 0, $words_left));
// If the above TODO is implemented, this will need to be adjusted to keep the specific whitespace characters
$text_node->textContent = $words_that_fit;
$remove_after = $text_node;
while( $remove_after->parentNode) {
while( $remove_after->nextSibling) {
$remove_after->parentNode->removeChild($remove_after->nextSibling);
}
$remove_after = $remove_after->parentNode;
}
break;
}
$output = substr($dom->saveHTML($dom->getElementsByTagName("body")->item(0)), strlen("<body>"), -strlen("</body>"));

TA貢獻1846條經驗 獲得超7個贊
好的,我想出了一個解決方法。我不知道這是否是最優雅的解決方案,所以如果有人看到更好的解決方案,我仍然很想聽聽,但現在我意識到我不必在我正在搜索的字符串中實際包含 html確定切割的位置,我只需要它是相同的長度。我抓取了所有的 html 元素,并創建了一個虛擬字符串,用相同數量的星號替換了所有元素:
// create faux string with placeholders instead of html for search purposes
preg_match_all('/<\/?[^>]*>/', $post_content, $alltags_result);
$tagcount = count( $alltags_result );
$post_content_dummy = $post_content;
foreach($alltags_result[0] as $thistag){
$post_content_dummy = str_replace($thistag, str_repeat("*",strlen($thistag)), $post_content_dummy);
}
然后我只是$post_content_dummy在 while 循環中使用而不是$post_content,以便找到切割位置,然后$post_content進行實際切割。到目前為止似乎工作正常。
- 2 回答
- 0 關注
- 170 瀏覽
添加回答
舉報