wrap long words or long characters ignoring html t

2019-08-03 15:28发布

I need wrap long words, each one in span tags, example:

$string = 'aaaaaaaaaaaaaaaa{}^?¿*!-<a href="#">link here</a>aaaaaaaaaa<br />aaaa';

I need print this:

( cut each 8 characters ignoring html tags )

"<span>aaaaaaaa</span>
<span>aaaaaaaa</span>
<span>{}^?¿*!-</span>
<a href="#">link here</a>
<span>aaaaaaaa</span>
aa
<br />
aaaa"

something like what makes facebook (<span class="word_break"></span>)

facebook code:

<span>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span><wbr></wbr><span class="word_break"></span>

any idea? :)

thanks so much

2条回答
仙女界的扛把子
2楼-- · 2019-08-03 15:41

I wrong a PHP functio for it word_wrap

<?php
$string = 'abcdefghijklmnop{}^??*!-<a href="#">link here</a>abcdefghij<br />abcd';

print_r(word_wrap($string));

// Function Starts Here
function word_wrap($string, $chunk_size = 8) {
    $offset = 0;
    $result = array();
    while(preg_match('#<(\w+)[^>]*>.*?</\1>|<\w+[^>]*/>#', $string, $match, PREG_OFFSET_CAPTURE, $offset)) {
        if($match[0][1] > $offset) {
            $non_html = substr($string, $offset, $match[0][1] - $offset);
            $chunks = str_split($non_html, $chunk_size );
            foreach($chunks as $s) {
                // Wrap text with length 8 in <span>, otherwise leave as it is
                $result[] = (strlen($s) == $chunk_size  ? "<span>" . $s . "</span>" : $s);
            }
        } 
        // Leave HTML tags untouched
        $result[] = $match[0][0];
        $offset = $match[0][1] + strlen($match[0][0]);
    }
    // Process last unmatched string
    if(strlen($string) > $offset) {
        $non_html = substr($string, $offset);
        $chunks = str_split($non_html, $chunk_size );
        foreach($chunks as $s) {
            $result[] = strlen($s) == $chunk_size  ? "<span>" . $s . "</span>" : $s;
        }
    } 
    return $result;
}

which produces the output of

Array
(
    [0] => <span>abcdefgh</span>
    [1] => <span>ijklmnop</span>
    [2] => <span>{}^??*!-</span>
    [3] => <a href="#">link here</a>
    [4] => <span>abcdefgh</span>
    [5] => ij
    [6] => <br />
    [7] => abcd
)
查看更多
姐就是有狂的资本
3楼-- · 2019-08-03 16:00

Ok I was a little off. You need str_split(); this should give you a workable array.

$str = 'aaaaaaaaaaaaaaaa{}^?¿*!-<a href="#">link here</a>aaaaaaaaaa<br />aaaa';

print_r(str_split($str, 8));

**This will return** 

(
    [0] => aaaaaaaa
    [1] => aaaaaaaa
    [2] => {}^*!-<a
    [3] =>  href="#
    [4] => ">link h
    [5] => ere</a>a
    [6] => aaaaaaaa
    [7] => a<br />a
    [8] => aaa
)

Look at the docs here

Just loop through that adding a span to each loop.

EDIT

I just realized that this won't solve the problem of "ignoring the HTML tags". You could probably tweak it real quick. Just don't go down the DARK ROAD of parsing HTML with REGEX please. Aloha.

查看更多
登录 后发表回答