基本上,我只希望对单词进行计数,而忽略html属性,例如:Uncaught TypeError: Cannot read property 'clearRect' of undefined
at Character.step (sprite.js:49)
等。
如果单词超出了字符数限制,则应在末尾加上省略号。
这是我当前的代码:
<p></p> <span></span
此代码的问题是,它也会计算html。
当前行为:
function limitText($length, $value)
{
return strlen($value) > $length ? substr($value, 0, $length) . '...' : $value;
}
所需结果:
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...
答案 0 :(得分:1)
我的想法是替换>
和</
之间的字符串
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);
}
答案 1 :(得分:0)
您应该将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);
}
答案 2 :(得分:0)
尝试一下:-
function limitText($length, $value){
return substr(strip_tags($value), 0, $length);
}
echo limitText(1, '<h1>Hello, PHP!</h1>');