2017-07-14 69 views
1

我想截斷包含保存其結構的html標籤的字符串。截斷保存HTML標籤結構的字符串

例子:

Hello! My name is Jerald and here is a link to my <a href="#">Blog</a>. 

所以,如果我的這串設置最多字符52,我希望它返回字符串像以下:

Hello! My name is Jerald and here is a link to my <a href="#">Bl</a> 

我試圖用strip_tagsstrlen功能計數沒有和帶有html標籤的文本,並設置子字符串的新長度(大小不帶+大小與html標籤)。但是這個方法正在打破html字符串。

+2

爲什麼不使用CSS?使用省略號比使用截斷和數據丟失更好。 –

+1

如果你有一個HTML項目(比如新聞/博客文章),然後你想要打印該項目的傳情,你可能想在PHP中做這件事。你當然可以像正常一樣截斷,但它可能會停止在一些html塊的中間。 – alistaircol

回答

1

我用這個,不是我的代碼,但找不到,我發現它原來:

function truncateHTML($html_string, $length, $append = '&hellip;', $is_html = true) { 
    $html_string = trim($html_string); 
    $append = (strlen(strip_tags($html_string)) > $length) ? $append : ''; 
    $i = 0; 
    $tags = []; 

    if ($is_html) { 
    preg_match_all('/<[^>]+>([^<]*)/', $html_string, $tag_matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 

    foreach($tag_matches as $tag_match) { 
     if ($tag_match[0][1] - $i >= $length) { 
     break; 
     } 

     $tag = substr(strtok($tag_match[0][0], " \t\n\r\0\x0B>"), 1); 
     if ($tag[0] != '/') { 
     $tags[] = $tag; 
     } 
     elseif (end($tags) == substr($tag, 1)) { 
     array_pop($tags); 
     } 

     $i += $tag_match[1][1] - $tag_match[0][1]; 
    } 
    } 

    return substr($html_string, 0, $length = min(strlen($html_string), $length + $i)) . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '') . $append; 
} 

例子:

$my_input_with_html = 'Hello! My name is Jerald and here is a link to my <a href="#">Blog</a>.'; 
$my_output_with_correct_html = truncateHTML($my_input_with_html, 52); 

爲您提供:

Hello! My name is Jerald and here is a link to my <a href="#">Bl</a>&hellip; 

演示: https://eval.in/832674

希望這有助於。