[英]Preserve Line Breaks - Simple HTML DOM Parser
使用PHP Simple HTML DOM Parser時,換行是否正常
標簽被剝離了?
我知道這是舊的,但我也在尋找這個,並意識到實際上有一個內置的選項來關閉刪除換行符。 無需編輯源代碼。
PHP Simple HTML Dom Parser的load
函數支持多個有用的參數:
load($str, $lowercase=true, $stripRN=false, $defaultBRText=DEFAULT_BR_TEXT)
調用load
函數時,只需將false
作為第三個參數傳遞。
$html = new simple_html_dom();
$html->load("<html><head></head><body>stuff</body></html>", true, false);
如果使用file_get_html
,那么它是第九個參數。
file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
編輯:對於str_get_html
,它是第五個參數(感謝yitwail)
str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
也正在努力解決這個問題,因為我需要在處理后輕松編輯HTML。
顯然, SimpleHTMLDOM
腳本$stripRN
有一個布爾值,默認情況下設置為true
。 它剝離HTML中的\\r
, \\n
或\\r\\n
標記。
將var設置為false
(腳本中出現幾個..),您的問題就解決了。
您不必將所有$stripRN
更改為false,唯一影響此行為的是在第816行``:
// load html from string
function load($str, $lowercase=true, $stripRN=false, $defaultBRText=DEFAULT_BR_TEXT) {
還要考慮更改第988行,因為多字節函數通常不安裝在不處理非西歐語言的機器上。 v1.5中的原始行立即打破了腳本:
if (function_exists('mb_detect_encoding')) { $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) ); } else $charset === false;
如果你在路過這里想知道你是否可以在DomDocument中做同樣的事情那么我很高興你能說! - 但它有點臟:(
我有一小段代碼我想整理但保留它包含的確切換行符(\\ n)。 這就是我做的......
// NOTE: If you're HTML isn't a full HTML document then expect DomDocument to
// start creating its own DOCTYPE, head and body tags.
// Convert \n into a pretend tag
$myContent = preg_replace("/[\n]/","<img src=\"slashN\" />",$myContent);
// Do your DOM stuff...
$dom = new DOMDocument;
$dom->loadHTML($myContent);
$dom->formatOutput = true;
$myContent = $dom->saveHTML();
// Remove the \n's that DOMDocument put in itself
$myContent = preg_replace("/[\n]/","",$myContent);
// Put my own \n's back
$myContent = preg_replace("/<img src=\"slashN\" \/>/i","\n",$myContent);
重要的是要注意我知道,我毫不懷疑我的輸入僅包含\\ n。 如果需要考慮\\ r \\ n或\\ t,您可能需要自己的變體。 例如slash.T或slash.RN等
另一個選項應該是希望保留其他格式,例如段落和標題是使用innertext
而不是plaintext
然后使用結果執行自己的字符串清理。
我意識到性能受到了打擊,但它確實允許更精細的控制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.