PHP修剪一个字符串 [英] php trim a string

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

问题描述

我正在尝试构建一个函数来修剪字符串,因为它超出了我的规范.

I'm trying to build a function to trim a string is it's too long per my specifications.

这就是我所拥有的:

function trim_me($s,$max) 
{
    if (strlen($s) > $max) 
    {
        $s = substr($s, 0, $max - 3) . '...';
    }
    return $s;
}

如果长度大于$max,则上述内容将修剪字符串,并添加连续符...

The above will trim a string if it's longer than the $max and will add a continuation...

我想扩展该功能以处理多个单词.当前它会执行它的操作,但是如果我有一个字符串,请说:How are you today?,它是18个字符长.如果运行trim_me($s,10),它将显示为How are yo...,这在美学上并不令人满意.我该怎么做,以便在整个单词后添加....假设如果我运行trim_me($s,10),我希望它显示How are you...,并在单词后添加继续符.有什么想法吗?

I want to expand that function to handle multiple words. Currently it does what it does, but if I have a string say: How are you today? which is 18 characters long. If I run trim_me($s,10) it will show as How are yo..., which is not aesthetically pleasing. How can I make it so it adds a ... after the whole word. Say if I run trim_me($s,10) I want it to display How are you... adding the continuation AFTER the word. Any ideas?

我几乎不想在一个单词的中间添加一个延续.但是,如果字符串中只有一个单词,那么延续只能打断单词.

I pretty much don't want to add a continuation in the middle of a word. But if the string has only one word, then the continuation can break the word then only.

推荐答案

实际上很简单,我添加了这个答案,因为

It's actually somehow simple and I add this answer because the suggested duplicate does not match your needs (but it does give some pointers).

您想要的是将字符串切成最大长度,但保留最后一个单词.因此,您需要找出剪切字符串的位置(以及是否真的有必要剪切字符串).

What you want is to cut a string a maximum length but preserve the last word. So you need to find out the position where to cut the string (and if it's actually necessary to cut it at all).

获取长度( strlen )并剪切字符串(

As getting the length (strlen) and cutting a string (substr) is not your problem (you already make use of it), the problem to solve is how to obtain the position of the last word that is within the limit.

这涉及到分析字符串并找出每个单词的偏移量.字符串处理可以使用正则表达式来完成.在撰写本文时,它使我想起了一个实际上更相似的问题,该问题已经得到解决:

This involves to analyze the string and find out about the offsets of each word. String processing can be done with regular expressions. While writing this, it reminds me on some actually more similar question where this has been already solved:

  • Extract a fixed number of chars from an array, just full words (with regex)
  • How to get first x chars from a string, without cutting off the last word? (with wordwrap)

它确实做到了:通过使用正则表达式获取完整单词"字符串.唯一的区别是,它删除了最后一个单词(而不是扩展它).当您想扩展最后一个单词时,这需要一个不同的正则表达式模式.

It does exactly this: Obtaining the "full words" string by using a regular expression. The only difference is, that it removes the last word (instead of extending it). As you want to extend the last word instead, this needs a different regular expression pattern.

在正则表达式中,\b与单词边界匹配.那是一个字之前或之后.现在,您至少要选择 $length个字符,直到下一个单词边界.

In a regular expression \b matches a word-boundary. That is before or after a word. You now want to pick at least $length characters until the next word boundary.

由于它可能在下一个单词之前包含空格,因此您可能需要对结果进行修整以删除最后的这些空格.

As this could contain spaces before the next word, you might want to trim the result to remove these spaces at the end.

您可以像下面那样扩展您的功能,然后使用正则表达式模式( preg_replace )和 trim :

You could extend your function like the following then with the regular expression pattern (preg_replace) and the trim:

/**
 * Cut a string at length while preserving the last word.
 * 
 * @param string $str
 * @param int $length
 * @param string $suffix (optional)
 */
function trim_word($str, $length, $suffix = '...') 
{
    $len = strlen($str);

    if ($len < $length) return $str;

    $pattern = sprintf('/^(.{%d,}?)\b.*$/', $length);
    $str = preg_replace($pattern, '$1', $str);
    $str = trim($str);
    $str .= $suffix;

    return $str;
}

用法:

$str = 'How are you today?';
echo trim_word($str, 10); # How are you...

您可以通过将模式中的最小长度减少后缀的长度来进一步扩展此范围(正如您的问题中所建议的那样,但是您在问题中给出的结果与您的代码不匹配).

You can further on extend this by reducing the minimum length in the pattern by the length of the suffix (as it's somehow suggested in your question, however the results you gave in your question did not match with your code).

我希望这会有所帮助.另外,请使用本网站上的搜索功能,虽然它并不完美,但是在现有问题中隐藏着许多其他方法的宝石.

I hope this is helpful. Also please use the search function on this site, it's not perfect but many gems are hidden in existing questions for alternative approaches.

这篇关于PHP修剪一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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