Wordpress删除空格

时间:2013-02-18 16:51:09

标签: php wordpress

我有这个代码在wordpress中运行循环外部的摘录。

<?php
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 35; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
return $the_excerpt;
}
?>

正如您所看到的,它会删除所有内容,如图像和其他内容,只留下文本,但是当它执行此操作时,它还会输出大量的空格(返回)。我试图用\ n,\ t,\ r \ n删除它们,但显然我不知道在哪里放置代码使其工作。你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

<强>尝试:

<?php
function get_excerpt_by_id($post_id){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
$excerpt_length = 35; //Sets excerpt length by word count
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '…');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
// LOOK HERE
$the_excerpt = str_replace("\r", "", $the_excerpt); // Replace carriage returns
$the_excerpt = str_replace("\n", "", $the_excerpt); // Replace new lines
// .. etc
return $the_excerpt;
}
?>

答案 1 :(得分:0)

试试这个

<?php
    function get_excerpt_by_id($post_id){
       $the_post = get_post($post_id); //Gets post ID
       $the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
       $the_excerpt = apply_filters('the_excerpt', $the_excerpt);
       return $the_excerpt;
    }
?>