我错了一个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
)