PHP Как вырезать строку без разрыва слов или тегов HTML - PullRequest
3 голосов
/ 14 июля 2011

Поскольку заголовок говорит, что я хочу вырезать строку, не разбивая ни слова, ни теги HTML, теперь я нашел эту функцию, которая решает проблему с тегами html (слегка измененная мной)

function substrhtml($str,$start,$len){

    $str_clean = substr(strip_tags($str),$start,$len);

    if(preg_match_all('/\<[^>]+>/is',$str,$matches,PREG_OFFSET_CAPTURE)){

        for($i=0;$i<count($matches[0]);$i++){

            if($matches[0][$i][1] < $len){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

            }else if(preg_match('/\<[^>]+>$/is',$matches[0][$i][0])){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

                break;

            }

        }

        return $str_clean;

    }else{

        return substr($str,$start,$len);

    }

}

Источник

но он все еще разрезает слова пополам в середине предложения, чего я не хочу, какие-либо идеи о том, как это отсортировать?

Как всегда, любая помощь приветствуется и спасибо заранее.

Ответы [ 3 ]

4 голосов
/ 28 августа 2012

Попробуйте это:

function substrhtml($str,$start,$len){

    $str_clean = substr(strip_tags($str),$start,$len);
    $pos = strrpos($str_clean, " ");
    if($pos === false) {
        $str_clean = substr(strip_tags($str),$start,$len);  
        }else
        $str_clean = substr(strip_tags($str),$start,$pos);

    if(preg_match_all('/\<[^>]+>/is',$str,$matches,PREG_OFFSET_CAPTURE)){

        for($i=0;$i<count($matches[0]);$i++){

            if($matches[0][$i][1] < $len){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

            }else if(preg_match('/\<[^>]+>$/is',$matches[0][$i][0])){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

                break;

            }

        }

        return $str_clean;

    }else{
        $string = substr($str,$start,$len);
         $pos = strrpos($string, " ");
        if($pos === false) {
            return substr($str,$start,$len);
        }
            return substr($str,$start,$pos);

    }

}
$string = '<h1>How to cut the string without breaking any words</h1>';
echo substrhtml($string,0,28);
?>
2 голосов
/ 14 июля 2011

разбиение строк при уважении слов может быть выполнено с помощью wordwrap () .

0 голосов
/ 30 января 2014
<?php

$string = 'When one thinks of luxury travel throughout the Mediterranean, a handful of destinations are bound to be at the top of the list, destinations like the French Riviera, the Grecian Islands, or the Italian coastline.';

echo current(explode('::BR::', wordwrap($string, 20, '::BR::')));
?>
...