[英]PHP - substr for html texts
基本上我想要的只是計算單詞並忽略句子中的 html 屬性,例如: <p></p> <span></span
等。
如果單詞超出字符限制,則應在末尾添加省略號。
這是我當前的代碼:
function limitText($length, $value)
{
return strlen($value) > $length ? substr($value, 0, $length) . '...' : $value;
}
這段代碼的問題是,它也會計算 html。
當前行為:
echo limitText(6, '<p>Hello</p>');
// displays: <p>Hel...
echo limitText(2, '<p>Hello</p>');
// displays: <p...
echo limitText(4, '<p>Hello</p>');
// displays: <p>H...
echo limitText(8, '<p>cutie</p> <p>patootie</p>');
// displays: <p>cutie...
想要的結果:
echo limitText(6, '<p>Hello</p>');
// displays: <p>Hello</p>
echo limitText(2, '<p>Hello</p>');
// displays: <p>He...</p>
echo limitText(4, '<p>Hello</p>');
// displays: <p>Hell...</p>
echo limitText(8, '<p>cutie</p> <p>patootie</p>');
// displays: <p>cutie</p> <p>pat...</p>
我的想法是替換>
和</
之間的字符串
function limitText($length, $value)
{
return preg_replace_callback('|(?<=>)[^<>]+?(?=</)|', function ($matches) use (&$length)
{
if($length <= 0)
return '';
$str = $matches[0];
$strlen = strlen($str);
if($strlen > $length)
$str = substr($str, 0, $length) . '...';
$length -= $strlen;
return $str;
},
$value);
}
您應該將 strip_tags 與 str_replace 結合使用,例如:
function limitText($length, $value)
{
//Get the real text
$textValue = strip_tags($value);
//get substr of real text
$realText = strlen($textValue) > $length ? substr($textValue, 0, $length) . '...' : $textValue;
// replace real text with the sub text
return str_replace($textValue, $realText, $value);
}
嘗試這個:-
function limitText($length, $value){
return substr(strip_tags($value), 0, $length);
}
echo limitText(1, '<h1>Hello, PHP!</h1>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.