包装长单词或长字符而忽略 html 标签 [英] wrap long words or long characters ignoring html tags
本文介绍了包装长单词或长字符而忽略 html 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将长单词包裹起来,每个单词都在 span 标签中,例如:
I need wrap long words, each one in span tags, example:
$string = 'aaaaaaaaaaaaaaaa{}^?¿*!-<a href="#">link here</a>aaaaaaaaaa<br />aaaa';
我需要打印这个:
(每8个字符忽略html标签)
( 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"
类似于 facebook (<span class="word_break"></span>)
something like what makes facebook (<span class="word_break"></span>)
脸书代码:
aaaaaaaaaaaaaaaaaaaaaaaaaaaa</span><wbr></wbr><span class="word_break"></span>
有什么想法吗?:)
非常感谢
推荐答案
我错了一个 PHP 函数 word_wrap
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;
}
产生
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
)
这篇关于包装长单词或长字符而忽略 html 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文