截断字符串保存 HTML 标签结构

Truncate a string saving HTML tags structure

我想截断包含 html 标签的字符串以保存其结构。

示例:

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

因此,如果我将其子字符串的最大字符数设置为 52,我希望它是 return 如下所示的字符串:

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

我尝试使用 strip_tagsstrlen 函数来计算不带和带 html 标签的文本,然后设置新的子字符串长度(不带大小的大小 + 带 [=23= 的大小] 标签)。但是这个方法破坏了 html string.

我用的是这个,不是我的代码,但找不到我最初找到它的地方:

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[=10=]\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

希望这对您有所帮助。