[英]How to show only few lines from a body text
我有一个mySql数据库,我只想显示其包含html代码的body字段中的10个单词,我该怎么做,是否有任何php函数可以做到这一点。
I would suggest to create one more column for this so you don't need to limit words on every request. 我建议为此再增加一列,这样就不必在每个请求上都限制单词。 Limitation will be easy to do with php:
使用php限制很容易做到:
$str = '<html>word word <b> word word word word word</b> word word word <u> word</u></html>';
$str = strip_tags($str); // strip html tags
preg_match('/^\s*+(?:\S++\s*+){1,10}/u', $str, $matches); // kohana's Text::limit_words()
$str = trim($matches[0]); // first 10 words of string
$ten = 10;
$text = strip_tags($bodyText); // remove html tags from the body text
$wordArray = str_word_count($text,2); //extract word offsets into an array
$offsetArray = array_keys($wordArray); // Convert offsets to an array indexed by word
$firstTenWords = substr($text,0,$offsetArray[$ten]-1); extract from the string between the start and tenth word
I forgot that you wanted to get the first 10 words but I would try using a substring of a stripped string and bring back a certain number of characters. 我忘记了您想获得前10个字,但我会尝试使用剥离字符串的子字符串并带回一定数量的字符。 Probably easier code and relatively the same result:
可能更简单的代码和相对相同的结果:
<?php
$start_position = 0;
$length = 30; // number of characters, not words
$suffix = "..."
// check if string is longer than limit and if so, shorten and attach suffix
if (strlen($your_text) > ($length - 3) {
echo substr(strip_tags($your_text), $start_position, $length) . $suffix;
} else {
echo $strip_tags($your_text);
}
?>
Should do the trick if you're getting rid of all formatting, like line breaks, etc. 如果您要摆脱所有格式设置(例如换行符等),则应该采取措施。
function gen_string($string,$min=10,$clean=false) {
$string = str_replace('<br />',' ',$string);
$string = str_replace('</p>',' ',$string);
$string = str_replace('<li>',' ',$string);
$string = str_replace('</li>',' ',$string);
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max && !$clean) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return trim($r);
}
just pass the html through the gen_string() function 只需通过gen_string()函数传递html
这样的事情可能会很方便。
echo substr($returnedQuery, 0,10);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.