合并两个正则表达式以截断字符串的单词
题
我试图提出以下功能,将字符串截断为整个单词(如果可能的话,否则应该截断为字符):
function Text_Truncate($string, $limit, $more = '...')
{
$string = trim(html_entity_decode($string, ENT_QUOTES, 'UTF-8'));
if (strlen(utf8_decode($string)) > $limit)
{
$string = preg_replace('~^(.{1,' . intval($limit) . '})(?:\s.*|$)~su', '$1', $string);
if (strlen(utf8_decode($string)) > $limit)
{
$string = preg_replace('~^(.{' . intval($limit) . '}).*~su', '$1', $string);
}
$string .= $more;
}
return trim(htmlentities($string, ENT_QUOTES, 'UTF-8', true));
}
这是一些测试:
// Iñtërnâtiônàlizætiøn and then the quick brown fox... (49 + 3 chars)
echo dyd_Text_Truncate('Iñtërnâtiônàlizætiøn and then the quick brown fox jumped overly the lazy dog and one day the lazy dog humped the poor fox down until she died.', 50, '...');
// Iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_... (50 + 3 chars)
echo dyd_Text_Truncate('Iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_jumped_overly_the_lazy_dog and one day the lazy dog humped the poor fox down until she died.', 50, '...');
他们俩都按原样工作,但是如果我放下第二个 preg_replace()
我得到以下内容:
iñtërnâtiônàlizætiøn_and_then_the_quick_brown_fox_jumped_overly_the_lazy_dog,有一天,懒狗的狗把可怜的狐狸放下了直到她死了...
我不能使用 substr()
因为它只能在字节级别上工作,而我无法访问 mb_substr()
ATM,我已经尝试了几次尝试加入第二个正则是第一个正时正时的正时正时正时的正时正则。
请帮助短信,我一直在努力工作了将近一个小时。
编辑:对不起,我已经醒了40个小时,我无耻地错过了这一点:
$string = preg_replace('~^(.{1,' . intval($limit) . '})(?:\s.*|$)?~su', '$1', $string);
尽管如此,如果某人的正则正则是更优化的正则(或忽略了尾随空间),请分享:
"Iñtërnâtiônàlizætiøn and then "
"Iñtërnâtiônàlizætiøn_and_then_"
编辑2:我仍然无法摆脱尾巴,有人可以帮我吗?
编辑3:好的,我的编辑都没有真正起作用,我被Regexbuddy所欺骗了 - 我可能应该把它留给另一天,现在睡觉了。今天就离开。
解决方案
也许我可以在漫长的《 Regexp噩梦》之后给您一个快乐的早晨:
'~^(.{1,' . intval($limit) . '}(?<=\S)(?=\s)|.{'.intval($limit).'}).*~su'
将其煮沸:
^ # Start of String
( # begin capture group 1
.{1,x} # match 1 - x characters
(?<=\S)# lookbehind, match must end with non-whitespace
(?=\s) # lookahead, if the next char is whitespace, match
| # otherwise test this:
.{x} # got to x chars anyway.
) # end cap group
.* # match the rest of the string (since you were using replace)
您总是可以添加 |$
到达 (?=\s)
但是由于您的代码已经检查了字符串长度是否长于 $limit
, ,我不觉得那是必要的。
其他提示
您是否考虑过使用WordWrap? ((http://us3.php.net/wordwrap)
不隶属于 StackOverflow