简体   繁体   中英

PHP - substr for html texts

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>

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);
}

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);
    }

Try this:-

function limitText($length, $value){
    return substr(strip_tags($value), 0, $length);

}
echo limitText(1, '<h1>Hello, PHP!</h1>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM