2011-06-17 116 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);