>  기사  >  백엔드 개발  >  PHP 문자열 가로채기에 관한 인터뷰 질문

PHP 문자열 가로채기에 관한 인터뷰 질문

WBOY
WBOY원래의
2016-09-21 14:13:10893검색

<code>$str = '这是<div>一道<a href="http://www.baidu.com">php字符串</a>截取题</div>。';
</code>

위 문자열의 처음 7자를 잘라서 표시합니다. 최종 결과는 다음과 같습니다.

<code>'这是<div>一道<a href="http://www.baidu.com">php</a></div>'
</code>

요구사항:

  1. 문자열에 HTML 태그가 있으면 건너뛰세요

  2. 가로채기 후 HTML 태그가 잘리는 경우 잘린 태그를 끝에 종료 태그와 함께 추가해야 합니다.

답글 내용:

<code>$str = '这是<div>一道<a href="http://www.baidu.com">php字符串</a>截取题</div>。';
</code>

위 문자열의 처음 7자를 잘라서 표시합니다. 최종 결과는 다음과 같습니다.

<code>'这是<div>一道<a href="http://www.baidu.com">php</a></div>'
</code>

요구사항:

  1. 문자열에 HTML 태그가 있으면 무시하세요.

  2. 가로채기 후 HTML 태그가 잘리는 경우 잘린 태그를 끝에 종료 태그와 함께 추가해야 합니다.

질문의 목적을 추측하지 않고 그냥 요구 사항에 따라 일반 교체를 썼습니다

<code class="php">function pure_cut($str, $len) {
    $reg = '/' . str_repeat('[^<>]((?:<[^>]+>)+)?', $len) . '$/u';
    $str = preg_replace_callback($reg, function($matches) {
        array_shift($matches);
        $replace = join('', $matches);
        return $replace;
    }, $str, 7);
    return $str;
}

echo pure_cut($str, 7);</code>

그런데 요구사항 2가 잘 이해가 안 되네요. 요구 사항 1이 충족되면 html 태그가 손상되지 않으며 복구할 필요가 없습니다.

리치텍스트 편집창의 내용을 캡쳐해야 합니다.

<code class="php"><?php 

$str = '这是<div>一道<a href="http://www.baidu.com">php字符串</a>截取题</div>。';

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('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                            } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/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*([^\s>!]+).*?>$/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);</code>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.