2011-06-17 111 views
1

我有一堆文字IKE的php 5個字符替換文字後?

比方說

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.

我想使它所以如果一個單詞長度超過5個字符,它取代了字符+。因此,該字符串將成爲

Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++ indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy.

但我不希望包括標點符號,如!和,和。但我想包括撇號'

任何想法我可以做到這一點?

回答

5

試試這個:

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting 
     industry. Lorem Ipsum has been the industry's standard dummy."; 
echo preg_replace("/(?<=[\w']{5})[\w']/", '+', $text); 

這將輸出:

Lorem Ipsum is simpl+ dummy text of the print+++ and types++++++ 
      indus+++. Lorem Ipsum has been the indus+++++ stand+++ dummy. 
+0

好的呼籲,積極lookbehind。這是使用回調函數的更優雅的解決方案。 – 2011-06-17 06:50:09

4

使用preg_replace_callback()

function callback($matches) { 
    return $matches[1] . str_repeat('+', strlen($matches[2])); 
} 
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy."; 
$str = preg_replace_callback("#([a-z']{5})([a-z']+)#i", 'callback', $str); 
echo $str; 
+0

則可以將預浸改變'preg_replace_callback(「#(/ [^ A-ZA-Z0-9- \ s] /] {5})/ [^ a-zA-Z0-9- \ s]/+)#「,'callback',$ str);'允許所有字母/數字 – ashurexm 2011-06-17 06:28:00

+0

@manyxcxi,」*編譯失敗:偏移量爲41 *的不匹配圓括號「。我會留下決定將什麼範圍的字符添加到作者,我只是想展示一個基本的例子。儘管我加了'i'修飾符。如果談論「還有什麼可以做」,我喜歡@巴特的答案。 – binaryLV 2011-06-17 06:36:45

+0

哦,另一個downvote沒有任何評論... – binaryLV 2011-06-20 06:41:18

0

您可以使用preg_replace這個

$str = "Lorem Ipsum is simply dummy text of the printing and 
     typesetting industry. Lorem Ipsum has been the industry's 
     standard dummy."; 

$pattern = "/([a-zA-Z]{5})([a-zA-Z]+)/"; 
$newStr = preg_replace($pattern,"$1+",$str); 

echo $newStr; 
// the + added 
你必須測試這是我沒有這臺機器上的PHP

+0

它只是修整每個單詞到最多5個字符,例如'typesetting'被替換爲'types'而不是'types ++++++''。 – binaryLV 2011-06-17 06:27:13

+0

你是對的我忘了加號,但仍然只會添加一個+符號。 – Ibu 2011-06-17 06:30:23

0

我們也可以使用strtr函數的效率()

preg_match_all('/[\w\']{5}[\w\']+/', $s, $matches); 
$dict = array(); 
foreach($matches[0] as $m){ 
    $dict[$m] = substr($m, 0, 5).str_repeat('+', strlen($m) - 5); 
} 
$s = strtr($s, $dict);