我需要包装长词,每个词都在span标签中,例如:
$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>)
facebook代码:
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span><wbr></wbr><span class="word_break"></span>
任何想法? :)
非常感谢
答案 0 :(得分: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
)
只需循环为每个循环添加一个span。
编辑
我刚才意识到这不会解决“忽略HTML标签”的问题。你可以快速调整它。请不要使用REGEX解析HTML DARK ROAD。阿罗哈。
答案 1 :(得分: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
)