正如标题所说,我希望在不破坏任何单词或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);
}
}
但它仍然会减少我不希望发生的半句话中的单词,有关如何对此进行排序的任何想法?
一如既往地提供任何帮助,并提前感谢.
解决方法:
试试这个:
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);
?>