You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
896 B
32 lines
896 B
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
/**
|
|
* 将富文本/HTML 转为单行纯文本(去标签、解码实体、折叠空白)。
|
|
*/
|
|
final class HtmlToPlainText
|
|
{
|
|
public static function toSingleLine(?string $html): ?string
|
|
{
|
|
if ($html === null || $html === '') {
|
|
return $html;
|
|
}
|
|
|
|
if (! str_contains($html, '<') && ! preg_match('/&[a-zA-Z#0-9]+;|&#\d+;|&#x[0-9a-fA-F]+;/', $html)) {
|
|
$t = trim((string) preg_replace('/\s+/u', ' ', $html));
|
|
$t = str_replace(["\r\n", "\r", "\n"], ' ', $t);
|
|
|
|
return $t === '' ? null : trim($t);
|
|
}
|
|
|
|
$t = strip_tags($html);
|
|
$t = html_entity_decode($t, ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
|
$t = (string) preg_replace('/\s+/u', ' ', $t);
|
|
$t = str_replace(["\r\n", "\r", "\n"], ' ', $t);
|
|
$t = trim($t);
|
|
|
|
return $t === '' ? null : $t;
|
|
}
|
|
}
|