如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?


当前回答

codeigniter框架为此包含了一个助手,称为“文本助手”。以下是codeigniter用户指南中适用的一些文档:http://codeigniter.com/user_guide/helpers/text_helper.html (只需阅读word_limititer和character_limititer部分)。 这里有两个与你的问题相关的函数:

if ( ! function_exists('word_limiter'))
{
    function word_limiter($str, $limit = 100, $end_char = '…')
    {
        if (trim($str) == '')
        {
            return $str;
        }

        preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);

        if (strlen($str) == strlen($matches[0]))
        {
            $end_char = '';
        }

        return rtrim($matches[0]).$end_char;
    }
}

And

if ( ! function_exists('character_limiter'))
{
    function character_limiter($str, $n = 500, $end_char = '…')
    {
        if (strlen($str) < $n)
        {
            return $str;
        }

        $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));

        if (strlen($str) <= $n)
        {
            return $str;
        }

        $out = "";
        foreach (explode(' ', trim($str)) as $val)
        {
            $out .= $val.' ';

            if (strlen($out) >= $n)
            {
                $out = trim($out);
                return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
            }       
        }
    }
}

其他回答

有时候,你需要将字符串限制到最后一个完整的单词ie:你不希望最后一个单词被打断,而是终止于最后一个单词的第二个。

例如: 我们需要将“This is my String”限制为6个字符,但不是“This i…”,我们希望它是“This…”,即我们将跳过最后一个单词中的破碎字母。

唷,我不擅长解释,这是代码。

class Fun {

    public function limit_text($text, $len) {
        if (strlen($text) < $len) {
            return $text;
        }
        $text_words = explode(' ', $text);
        $out = null;


        foreach ($text_words as $word) {
            if ((strlen($word) > $len) && $out == null) {

                return substr($word, 0, $len) . "...";
            }
            if ((strlen($out) + strlen($word)) > $len) {
                return $out . "...";
            }
            $out.=" " . $word;
        }
        return $out;
    }

}

我不确定这是否是最快的解决方案,但它看起来是最短的:

$result = current(explode("\n", wordwrap($str, $width, "...\n")));

附注:见一些例子在这里https://stackoverflow.com/a/17852480/131337

这个解决方案不会删减单词,它会在第一个空格后加三个点。 我编辑了@Raccoon29解决方案,我用mb_函数替换了所有函数,以便这将适用于所有语言,如阿拉伯语

function cut_string($str, $n_chars, $crop_str = '...') {
    $buff = strip_tags($str);
    if (mb_strlen($buff) > $n_chars) {
        $cut_index = mb_strpos($buff, ' ', $n_chars);
        $buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
    }
    return $buff;
}

如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

在本例中,$preview将是“Knowledge is a natural right of every human”。

动态代码示例: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

我使用的函数是:

function cutAfter($string, $len = 30, $append = '...') {
        return (strlen($string) > $len) ? 
          substr($string, 0, $len - strlen($append)) . $append : 
          $string;
}

看到它的行动。