PHP如何在不破坏任何单词或HTML标签的情况下剪切字符串

时间:2011-07-14 12:44:13

标签: php html function substr

正如标题所说,我希望在不破坏任何单词或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);

    }

}

Source

但它仍然会减少我不想发生的半句话中的单词,有关如何对此进行排序的任何想法?

一如往常,任何帮助都会受到赞赏并提前感谢。

3 个答案:

答案 0 :(得分:4)

试试这个:

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

答案 1 :(得分:2)

字符串拆分虽然尊重单词可以使用wordwrap()完成。

答案 2 :(得分: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::')));
?>