mb_substr切断后摘录中的单词?

时间:2013-07-18 00:27:09

标签: php html wordpress post format

这是我用来在我的wordpress帖子摘录中显示html格式的代码:

 function get_excerpt($post, $ln){
        if (!empty($post->post_excerpt)) {
            if (strlen($post->post_excerpt) > $ln) {
                echo mb_substr(($post->post_excerpt), 0, $ln);
            } 
        } else {
            if (strlen($post->post_content) > $ln) {
                  echo mb_substr(($post->post_content), 0, $ln);
            } 
        }

    }

如何编辑mb_substr以便摘录会在一段时间内结束?例如,摘录将像这样“她有一种可爱而无辜的魅力”,而不是“她有一种可爱和无辜的魅力,让人们关心她。”我希望摘录完成句子并在一段时间内结束,而不是仅停留在字符限制,设置为800.在代码中,$ ln设置为800.

更新:

这是我最终使用的代码。单词仍然在摘录中被截断,但我在点末添加了一个Read More链接。

 function get_excerpt($post, $ln){
    if (!empty($post->post_excerpt)) {
        if (strlen($post->post_excerpt) > $ln) {
            echo mb_substr(($post->post_excerpt), 0, $ln) . '...'; ?> <a href="<?php echo get_permalink( $post -> ID )?>">[Read More]</a>
 <?php } 
    } else {
        if (strlen($post->post_content) > $ln) {
              echo mb_substr(($post->post_content), 0, $ln) . '...';?> <a href="<?php echo get_permalink( $post -> ID )?>">[Read More]</a>
 <?php } 
    }

}

1 个答案:

答案 0 :(得分:1)

如果你能保证会有“。”在你的文本中,你可以这样做:

echo strtok("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet egestas lacus. Maecenas posuere dolor vitae ultrices viverra.",".");

这将输出:“Lorem ipsum dolor sit amet,consectetur adipiscing elit”

strtok manual page