1

我需要包装长词,每一个都在跨度标签中,例如:

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

我需要打印这个:

(剪掉每 8 个字符,忽略 html 标签)

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

类似于 facebook 的原因(<span class="word_break"></span>)

脸书代码:

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

任何想法?:)

非常感谢

4

2 回答 2

0

好吧,我有点不对劲。你需要 str_split(); 这应该给你一个可行的数组。

$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
)

在这里查看文档

只需循环,为每个循环添加一个跨度。

编辑

我刚刚意识到这并不能解决“忽略 HTML 标签”的问题。你可能会很快调整它。请不要走上用正则表达式解析 HTML 的黑暗之路。阿罗哈。

于 2012-09-26T01:31:07.870 回答
0

我错了一个PHP函数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;
}

产生的输出

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
)
于 2012-09-26T02:05:23.660 回答