使用PHP的文本摘录

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用PHP的文本摘录相关的知识,希望对你有一定的参考价值。

Create excerpts from text block from your wordpress content and add links page / post from the guid.
  1. /**
  2. * usage:
  3. * $txt = new($post->post_content, 50, 'Read in full', '<span class="readmore">', '</span>', '<a><span>');
  4. * echo $text->createExcerpt();
  5. *
  6. */
  7.  
  8.  
  9. class text{
  10.  
  11. public $text;
  12. public $length;
  13. public $allowedTags;
  14. public $readMoreText;
  15.  
  16. //create internal variables from those passed to the class
  17. function __construct($text = '',
  18. $length = 50,
  19. $readMoreText = 'Read In Full...',
  20. $before = '',
  21. $after = '',
  22. $allowedTags = '<a>') {
  23.  
  24. $this->text = $text;
  25. $this->length = $length;
  26. $this->readMoreText = $readMoreText;
  27. $this->before = $before;
  28. $this->after = $after;
  29. $this->allowedTags = $allowedTags;
  30.  
  31. }
  32.  
  33. //shorten text to required length
  34. public function shortenText() {
  35. //explode the string into an array of the length we want
  36. if (count(explode(' ', $this->text)) > $this->length)
  37. {
  38. $textArray = explode(' ', $this->text, $this->length);
  39. //remove the excess string from the end of the array
  40. array_pop($textArray);
  41. //create a string from the array
  42. $textString = implode(' ', $textArray);
  43. //cleaning up
  44. unset($textArray);
  45. //return
  46. return $textString . '... ';
  47. }
  48. else
  49. {
  50. return $this->text;
  51. }
  52. }
  53.  
  54. //remove tags and other.
  55. public function cleanText($text){
  56. //strip the text of html tags, except those we want
  57. $strippedText = strip_tags($text, $this->allowedTags);
  58. //remove [] and their content
  59. $strippedText = preg_replace('`[[^]]*]`','',$strippedText);
  60. //return
  61. return $strippedText;
  62. }
  63.  
  64. //create output
  65. public function createExcerpt(){
  66. global $post;
  67.  
  68.  
  69. //create output
  70. $output = '';
  71. $output .= $this->cleanText($this->shortenText());
  72. if($this->readMoreText !== '')
  73. {
  74. $output .= $this->before;
  75. $output .= ' <a href="'. $post->guid .'" title="'. $this->readMoreText . ': '. $post->post_title .'">'. $this->readMoreText . '</a>';
  76. $output .= $this->after;
  77. }
  78. return $output;
  79. }
  80.  
  81. }//end class//

以上是关于使用PHP的文本摘录的主要内容,如果未能解决你的问题,请参考以下文章

css常用代码片段 (更新中)

php 阅读更多文本摘录

[moka摘录]查看邮件是否已被阅读

PHP 显示具有自定义摘录长度的帖子和自定义在WordPress中阅读更多文本

php 从提供的内容中生成摘录。剥离HTML,删除尾随标点符号,并在删除文本时添加“更多”字符串。

从 WordPress 帖子中获取有限的纯文本摘录?