Reputation: 756
Basically what i want is only count the words and ignore the html properties such as: <p></p> <span></span
etc in a sentence.
And if the words is beyond the character limit, it should put an ellipsis at the end.
Here's my current code:
function limitText($length, $value)
{
return strlen($value) > $length ? substr($value, 0, $length) . '...' : $value;
}
The issue with this code is, it will also count the html.
Current behavior:
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...
Desired result:
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>
Upvotes: 2
Views: 227
Reputation: 630
Try this:-
function limitText($length, $value){
return substr(strip_tags($value), 0, $length);
}
echo limitText(1, '<h1>Hello, PHP!</h1>');
Upvotes: 0
Reputation: 27021
My idea is replace the string between >
and </
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);
}
Upvotes: 1
Reputation: 1072
You should combine strip_tags with str_replace like :
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);
}
Upvotes: 0