Php 如何仅显示正文中的几行
我有一个mySql数据库,我想从它的主体字段中只显示10个包含html代码的单词,我如何做到这一点,是否有任何php函数可以做到这一点 我忘了您想获取前10个单词,但我会尝试使用剥离字符串的子字符串并返回一定数量的字符。可能更简单的代码和相对相同的结果:Php 如何仅显示正文中的几行,php,mysql,string,Php,Mysql,String,我有一个mySql数据库,我想从它的主体字段中只显示10个包含html代码的单词,我如何做到这一点,是否有任何php函数可以做到这一点 我忘了您想获取前10个单词,但我会尝试使用剥离字符串的子字符串并返回一定数量的字符。可能更简单的代码和相对相同的结果: $ten = 10; $text = strip_tags($bodyText); // remove html tags from the body text $wordArray = str_word_count($text,2); //
$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
<?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);
}
?>
如果您要删除所有格式,如换行符等,则应该这样做。由于您的字段包含html,因此很难获取有效的html-mysql不理解html
不过,您可以使用mysql:我建议为此再创建一个列,这样您就不需要限制每个请求的字数。使用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
像这样的东西可能很方便
echo substr($returnedQuery, 0,10);
更好的解决方案
只需通过gen_string函数传递html即可您可以指定具体要执行的操作吗?可能会显示一个示例?OP是在10个单词之后,而不是10个字符之后。我没有说这是准确的答案,只是它可能会派上用场。制表符、换行符,只是举几个例子说明为什么不应该喊“更好”。制表符和换行符不会在html模式下显示。这样更好。
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);
}