PHP How to cut string without breaking any words or HTML tags
As title says I want to cut a string without breaking any words or HTML tags, now I found this function which sorts the html tags problem out (slightly modified by myself)
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,$matc开发者_如何学运维hes[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
but it still cuts words in half mid sentence which I don't want to happen, any ideas on how to sort this?
As always any help is appreciated and thanks in advance.
Try this:
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);
?>
string splitting while respecting words can be accomplished using wordwrap().
<?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::')));
?>
精彩评论