PHP substr but keep HTML tags?

后端 未结 3 923
不知归路
不知归路 2020-12-28 17:19

I am wondering if there is an elegant way to trim some text but while being HTML tag aware?

For example, I have this string:

$data = \'         


        
3条回答
  •  醉酒成梦
    2020-12-28 18:09

    Using @newbieuser his function, I had the same issue, like @pablo-pazos, that it was (not) breaking when $limit fell into an html tag (in my case
    at the r)

    Fixed with some code

    if ( strlen($code) <= $limit ){
        return $code;
    }
    
    $html = substr($code, 0, $limit);       
    
    //We must find a . or > or space so we are sure not being in a html-tag!
    //In my case there are only 
    //If you have more tags, or html formatted text, you must do a little more and also use something like http://htmlpurifier.org/demo.php $_find_last_char = strrpos($html, ".")+1; if($_find_last_char > $limit/3*2){ $html_break = $_find_last_char; }else{ $_find_last_char = strrpos($html, ">")+1; if($_find_last_char > $limit/3*2){ $html_break = $_find_last_char; }else{ $html_break = strrpos($html, " "); } } $html = substr($html, 0, $html_break); preg_match_all ( "#<([a-zA-Z]+)#", $html, $result ); ......

提交回复
热议问题