【发布时间】: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(我看不懂日语,所以请确认这是正确的)