2012-02-09 137 views
14

我试图在PHP中截断一些文本,并且偶然发现了这种方法(http://theodin.co.uk/blog/development/truncate-text-in-php-the-easy-way.html),通过评论来判断这似乎是一个非常容易实现的解决方案。问题是我不知道如何实现它:S。在PHP中截断文本?

会有人介意我该怎么做的方向来实现这个?任何帮助将不胜感激。

在此先感谢。

+1

什么不你了解了'SUBSTR()'的问题。(即源比所需的小)?你在哪里感到困惑?根据您给出的参数,它是一个返回部分源字符串的函数。 – Brad 2012-02-09 22:27:28

+1

是的,只要使用'substr()'第一个参数是你的文本,第二个是偏移量 - 如果设置为0,它将从头开始截断,如果设置为1,2,3 ...它会截断很多字符,第三个参数是应该截断的长度。例如'substr(“hello world”,3,4)'将返回'lo w' - 3个字符后面4个字符。 – 2012-02-09 22:30:23

+0

可能重复[将多字节字符串截断为n个字符](http://stackoverflow.com/questions/2154220/truncate -a-multibyte-string-to-n-chars) – Gordon 2012-02-09 22:51:51

回答

51

显而易见的事情是读documentation

而是帮助:substr($str, $start, $end);

$str是你的文字

$start是开始的字符索引。就你而言,它可能是0,这意味着开始。

$end是在哪里截断。例如,假设您想以15个字符结尾。你会写这样的:

<?php 

$text = "long text that should be truncated"; 
echo substr($text, 0, 15); 

?> 

,你会得到这样的:

long text that 

有道理?

编辑

你给的链接找到斩波文本至所需长度后,最后的空白,所以你不要在一个单词中间隔断的功能。但是,它缺少一个重要的事情 - 传递给函数的期望长度,而不是总是假设您希望它为25个字符。因此,这里的更新版本:

function truncate($text, $chars = 25) { 
    if (strlen($text) <= $chars) { 
     return $text; 
    } 
    $text = $text." "; 
    $text = substr($text,0,$chars); 
    $text = substr($text,0,strrpos($text,' ')); 
    $text = $text."..."; 
    return $text; 
} 

所以你的情况,你会这个函数粘贴到functions.php文件,并在你的页面调用它是这样的:

$post = the_post(); 
echo truncate($post, 100); 

这将砍下你的帖子下来到100个字符之前的最后一个空格。显然你可以传递任何数字而不是100。

+0

ha句开始? – 2012-02-09 22:34:52

+0

肯定。几乎肯定是一个非常糟糕的。 – 2012-02-09 22:36:38

+0

感谢您的帮助,我试图理解这一点。如果我蠢的话,提前道歉。所以我会把我链接到的网站的字符串放入类似于functions.php文件(我使用WordPress)?我说的是我在哪里申报该功能? – realph 2012-02-09 22:42:18

3
$mystring = "this is the text that I would like to had truncated"; 

// Pass your variable to the function 
$mystring = truncat($mystring); 

// Truncated tring printed out; 
echo $mystring; 


//truncate text function 
public function truncate($text) { 

    //specify number fo characters to shorten by 
    $chars = 25; 

    $text = $text." "; 
    $text = substr($text,0,$chars); 
    $text = substr($text,0,strrpos($text,' ')); 
    $text = $text."..."; 
    return $text; 
} 
3
$text="abc1234567890"; 

// truncate to 4 chars 

echo substr(str_pad($text,4),0,4); 

这避免了截断4个字符的字符串到10个字符的

+0

这就是我需要的! :d – 2015-11-02 00:20:03