加载单词,而不是字母[WordPress/PHP]


Load in words, not letters [WordPress/PHP]

希望有人能帮帮我。

我在一个网站上工作,我安装了Wordpress。在首页上,我有一个小div,我想从另一个页面输出前10个单词与pageID。现在它几乎可以工作了,但是不是加载10个单词而是加载10个字母。

例子:
而不是: Hello my name is Erwin,这是一个测试
它加载: Hello my name

我做错了什么?

if(!function_exists('getPageContent'))
{
    function getPageContent($pageId,$num_words)
    {
        if(!is_numeric($pageId))
        {
            return;
        }
        global $wpdb;
        $nsquery = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
        ' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
        $post_data = $wpdb->get_results($nsquery);
        if(!empty($post_data))
        {
            foreach($post_data as $post)
            {
                $text_out=nl2br($post->post_content);
                $text_out=str_replace(']]>', ']]>', $text_out);
                $text_out = strip_tags($text_out);
                return substr($text_out,0,$num_words);
            }
        }
    }}



我使用下面的字符串来加载内容:
(其中89是我的Page ID)

echo getPageContent(89,10);

这将提取字符串的前10个单词

$text_out = "Hello my name is Erwin and this is a test and this is another test";
$num_words = 10;
echo implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));

Hello my name is Erwin and this is a test

如何选择句子的前10个单词?-同样的问题。用implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));代替substr($text_out,0,$num_words);

有一个来自wordpress的函数:

the_excerpt();

就是这样。这表明……文章或页面的节选,并在末尾加上链接。您可以使用参数the_excerpt($length)自定义长度,修改函数一点。

来源:http://codex.wordpress.org/Function_Reference/the_excerpt

Here $num_words = 10

意味着substr将字符串从字符0 to 10中断开

如果你想要整个字符串那么你必须echo

echo getPageContent(89,32);