【问题标题】:How do I get all the words for certain character limit如何获得特定字符限制的所有单词
【发布时间】:2018-08-16 04:55:59
【问题描述】:

假设我有 500 个字符的描述。我需要将字符限制为 200 个。然后我删除最后一个单词以确保我没有断词。

这适用于英文内容,但不适用于日语或繁体中文等其他语言。当我限制日文或中文描述时,它会在末尾给出一个特殊字符,如下所示。

下面是我的代码,有没有办法克服这个问题?

function getLimitDescription($description, $limit)
{
    $limitedDesc  = substr($description, 0, $limit);

    // Remove the last word of the limited description
    $limitedDesc = preg_replace('/\W\w+\s*(\W*)$/', '$1', $limitedDesc);
    $lastChar    = substr($limitedDesc, -1);

    if (preg_match("/[\'^£$%&*()}{@#~?><>;,|=_+¬-]/", $lastChar))
    {
        $limitedDesc = substr($limitedDesc, 0, -1);
    }

    return $limitedDesc;
}

【问题讨论】:

  • 你能举一个输入和预期输出的例子吗?
  • @CertainPerformance 如果我有一个类似“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”的字符串。如果我将描述限制为 15 个字符,则输出应为“ Lorem ipsum ”。
  • 我的意思是日文/中文,你的代码部分不起作用
  • 你试过 u|Unicode 标志了吗? regex101.com/r/M3VMK6/1 & ideone.com/Eg08Nt(我看不懂日语,所以请确认这是正确的)

标签: php regex


【解决方案1】:

您不需要使用正则表达式。只需使用 strrpos 并从右边找到下一个空格。

function getLimitDescription($description, $limit)
{
    $limitedDesc  = substr($description, 0, $limit);
    $pos = strrpos($limitedDesc, " ");
    $limitedDesc  = substr($limitedDesc, 0, $pos);
    return $limitedDesc;
}

echo getLimitDescription("Insert long string right here", 17);

https://3v4l.org/eao6F

【讨论】:

  • 你的方法有效。似乎它发生在我用来删除最后一个单词的正则表达式中。谢谢!
猜你喜欢
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
相关资源
最近更新 更多