我有一个字符串,我想搜索一个关键字,该字符串应该在关键字前后被截断。
例子:
…erat, sed diam voluptua. At vero eos et FOO BAR et justo duo dolores et ea reb…
如果关键字在开头,则不应截断文本。
At vero eos et FOO BAR et justo duo dolores et ea reb, lorem ipsum dolor sit amet…
这是我的片段。真的不是很好...
$keyword = 'FOO BAR';
$truncateChar = '…';
$truncateCharLength = mb_strlen($truncateChar);
$truncateLength = 80;
$str = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et FOO BAR et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
// Find the position of the keyword
$position = mb_strpos($str, $keyword);
if (($position - ($truncateLength / 2)) < 0) {
// if there are not enough chars ($truncateLength/2) before the keyword,
// don't truncate at the beginning.
$str = mb_substr($str, 0);
} else {
// truncate ($truncateLength/2) chars before the keyword
$str = $truncateChar . mb_substr($str, $position - ($truncateLength / 2));
}
// if the string is longer than $truncateLength, than truncate the string
if (mb_strlen($str) > $truncateLength) {
$str = mb_substr($str, 0, $truncateLength - $truncateCharLength) . $truncateChar;
}
echo $str;
这是一个搜索结果。我不想显示整个文本。仅显示关键字的部分。有没有更好的性能方法来做到这一点?正则表达式例如?
缥缈止盈