4

タイトルにあるように、単語や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);

    }

}

ソース

しかし、それでも私が起こりたくない単語を半分の文にカットします、これをどのようにソートするかについてのアイデアはありますか?

いつものように、どんな助けでもありがたいです、そして前もって感謝します。

4

3 に答える 3

5

これを試して:

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);
?>
于 2012-08-28T11:29:32.347 に答える
2

単語を考慮しながら文字列を分割するには、wordwrap()を使用します。

于 2011-07-14T12:50:12.153 に答える
0
<?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::')));
?>
于 2014-01-30T13:31:22.357 に答える