2012-09-26 64 views
1

我需要回繞長字,每一個在span標籤,例如:迴繞長字或長字符忽略html標籤

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

發cebook代碼:

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

什麼想法? :)

非常感謝

+0

輸出什麼是你試圖總結的模式?而你的意思是「類似facebook()的東西」? – noel

+0

我嘗試用這樣的:'的preg_replace( '〜[^ \ S \ n \ r \ t] +〜', '',$文本)' Facebook的包裝用span標籤 ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' –

+0

那麼,如果你使用PHP,你可以嘗試'chunk_split($字符串,8);'溢出的串起來,剛纔它放入一個跨度在循環 – noel

回答

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 
) 

Look at the docs here

只是循環通過添加一個跨度爲各循環。

編輯

我才意識到,這不會解決「忽略HTML標籤」的問題。你大概可以很快調整它。請不要用REGEX解析HTML的DARK ROAD。阿羅哈。

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 
)