php有很多截取字符串的函数,mb_substr就是其中一个,不仅适用于英文还适合中文截取。
但是在截取字符串,我遇到了以下bug
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
?>
<div class="section">
<div class="article-time"><?php echo date("Y-m-d",$row['a_time']); ?></div>
<div class="article-title"><a href="article.php?a_id=<?php echo $row['a_id'] ?>"><?php echo $row['a_title']; ?></a></div>
<div class="article-content">
<?php
$string = preg_replace ("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $row['a_content']);
//转义html标签
$string = htmlspecialchars($string);
echo mb_substr($string, 0,180,'utf-8');
?>......
</div>
</div>
<?php
}
由于在截取时,可能会截取到html标签,因为我的content是从后台编辑文章而来,文本编辑器里有很多的标签,当截取位置不恰当时,就导致了div标签配对的乱套。
解决 方法是去除要截取内容中的html标签。
<?php
$string = preg_replace ("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $row['a_content']);
$string = htmlspecialchars($string);
echo mb_substr($string, 0,180,'utf-8');
?>......
实例
把预定义的字符 "<" (小于)和 ">" (大于)转换为 HTML 实体:
<?php $str = "This is some <b>bold</b> text."; echo htmlspecialchars($str); ?>
以上代码的 HTML 输出如下(查看源代码):
<!DOCTYPE html> <html> <body> This is some <b>bold</b> text. </body> </html>
以上代码的浏览器输出:
This is some <b>bold</b> text.