截断PHP中的文字? [英] Truncating Text in PHP?

查看:64
本文介绍了截断PHP中的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试截断PHP中的一些文本,并且偶然发现了该方法(

I'm trying to truncate some text in PHP and have stumbled across this method (http://theodin.co.uk/blog/development/truncate-text-in-php-the-easy-way.html), which judging by the comments seems like a great easy-to-implement solution. The problem is I don't know how to implement it :S.

有人会介意将我指向实现该目标的方向吗?任何帮助将不胜感激.

Would someone mind pointing me in the direction of what to do to implement this? Any help whatsoever would be appreciated.

先谢谢了.

推荐答案

显而易见,要做的事情是阅读

The obvious thing to do is read the documentation.

但要提供帮助:substr($str, $start, $end);

$str是您的文字

$start是开始的字符索引.在您的情况下,很可能是0,这意味着最开始.

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end是截断位置.例如,假设您希望以15个字符结尾.您可以这样写:

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

<?php

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

?>

您会得到的:

long text that 

有意义吗?

编辑

您提供的链接是一项功能,用于将文本切成所需的长度后找到最后一个空格,这样您就不会在单词的中间切掉.但是,它缺少一件事-传递给函数的所需长度,而不是始终假定您希望它为25个字符.所以这是更新的版本:

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

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文件中,并在页面中这样调用它:

So in your case you would paste this function into the functions.php file and call it like this in your page:

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

这会将您的帖子减少到最后一个出现空白的空格,该空格等于或小于100个字符.显然,您可以传递任何数字,而不是100.无论您需要什么.

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

这篇关于截断PHP中的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆