php字符串处理面试题,一道php字符串截取的面试题

应该是截取富文本编辑框的内容吧.

$str = '这是

一道 php字符串截取题
。';

function truncate($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {

if ($considerHtml) {

if (mb_strlen(strip_tags($text)) <= $length) {

return $text;

}

preg_match_all('/(<.>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);

$total_length = mb_strlen($ending);

$open_tags = array();

$truncate = '';

foreach ($lines as $line_matchings) {

if (!empty($line_matchings[1])) {

if (preg_match('/^$/is', $line_matchings[1])) {

} else if (preg_match('/^$/s', $line_matchings[1], $tag_matchings)) {

$pos = array_search($tag_matchings[1], $open_tags);

if ($pos !== false) {

unset($open_tags[$pos]);

}

} else if (preg_match('/^!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {

array_unshift($open_tags, strtolower($tag_matchings[1]));

}

$truncate .= $line_matchings[1];

}

$content_length = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));

if ($total_length+$content_length > $length) {

$left = $length - $total_length;

$entities_length = 0;

if (preg_match_all('/&[0-9a-z]{2,8};|[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {

foreach ($entities[0] as $entity) {

if ($entity[1]+1-$entities_length <= $left) {

$left--;

$entities_length += mb_strlen($entity[0]);

} else {

break;

}

}

}

$truncate .= mb_substr($line_matchings[2], 0, $left+$entities_length);

break;

} else {

$truncate .= $line_matchings[2];

$total_length += $content_length;

}

if($total_length >= $length) {

break;

}

}

} else {

if (mb_strlen($text) <= $length) {

return $text;

} else {

$truncate = mb_substr($text, 0, $length - mb_strlen($ending));

}

}

if (!$exact) {

$spacepos = mb_strrpos($truncate, ' ');

if (isset($spacepos)) {

$truncate = mb_substr($truncate, 0, $spacepos);

}

}

$truncate .= $ending;

if($considerHtml) {

foreach ($open_tags as $tag) {

$truncate .= '' . $tag . '>';

}

}

return $truncate;

}

echo truncate($str, 7, '', true, true);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值