【问题标题】:PHP How to cut string without breaking any words or HTML tagsPHP如何在不破坏任何单词或HTML标签的情况下剪切字符串
【发布时间】:2011-10-05 07:38:39
【问题描述】:

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

但它仍然在我不想发生的中间句子中减少了一半的单词,关于如何排序的任何想法?

一如既往地感谢任何帮助,并提前致谢。

【问题讨论】:

标签: php html function substr


【解决方案1】:

试试这个:

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】:

    可以使用wordwrap()完成字符串拆分,同时尊重单词。

    【讨论】:

      【解决方案3】:
      <?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::')));
      ?>
      

      【讨论】:

        猜你喜欢
        • 2013-06-15
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 2015-06-05
        • 2015-05-11
        • 1970-01-01
        相关资源
        最近更新 更多