php - 如何在不干扰 HTML 标签的情况下从 php 字符串中剥离字符

标签 php html

我有一个包含如下 html 标签的字符串。

$desc = "<p>Lorem <strong>ipsum</strong> dolor sit amet</p><p>Duo at agam maiorum instructior, ut tale quidam ancillae qui, est cu paulo consetetur.</p>"

我想取前 10 个字符:

  1. HTML 标签不计入。
  2. 所有打开的 HTML 标签都正确关闭。

现在如果使用 substr:

$result = substr($desc, 0, 10);

实际结果是:<p>Lorem <

我想要的是:<p>Lorem <strong>ipsu</strong></p>

最佳答案

我通过使用此处的非常好的代码实现了这一点 How to close unclosed HTML Tags?由 kamal 回答

<?php
 $str = "<p>Lorem <strong>ipsum</strong> dolor sit amet</p><p>Duo at agam maiorum instructior, ut tale quidam ancillae qui, est cu paulo consetetur.</p>";
 $s = strip_tags($str);
 $result = substr($s, 0, 10);
 $sarr = explode(' ', $result);
 $last = end($sarr);
 $l = strpos($str, $last);
 $r = substr($str, 0, $l);
 echo closetags($r.$last);

 function closetags ( $html )
    {
    #put all opened tags into an array
    preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
    $openedtags = $result[1];
    #put all closed tags into an array
    preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
    $closedtags = $result[1];
    $len_opened = count ( $openedtags );
    # all tags are closed
    if( count ( $closedtags ) == $len_opened )
    {
    return $html;
    }
    $openedtags = array_reverse ( $openedtags );
    # close tags
    for( $i = 0; $i < $len_opened; $i++ )
    {
        if ( !in_array ( $openedtags[$i], $closedtags ) )
        {
        $html .= "</" . $openedtags[$i] . ">";
        }
        else
        {
        unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
        }
    }
    return $html;
}
?>

关于php - 如何在不干扰 HTML 标签的情况下从 php 字符串中剥离字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31675288/

相关文章:

phpMyAdmin 只有在/etc/php.ini 不存在时才有效

php - 如何在 LIKE %% 查询中首先按最近距离排序 MYSQL 查询?

jquery - 这个移动的火箭是否使用 CSS3(动画)?

php - 谷歌AMP : amp-list vs php loop - SEO/Pagespeed

php - 对案例使用变量,对开关使用函数?

html - 两个内联 div 中的内容对齐问题?

javascript - 根据下拉选择和文本框值更改 url

html - Bootstrap - 导航栏不适用于所有屏幕

php - 系统生成的电子邮件退回

javascript - 我的谷歌地图(带有 JS 的静态 html)不会突然出现?