用出现次数替换子字符串

时间:2018-08-16 15:33:49

标签: php preg-replace

我想用一个子字符串替换它的出现次数,例如:

$newText = "The dog is saying wooff4 but he should say 
bark bark bark bark not wooff3";


结果应该是:

{{1}}

2 个答案:

答案 0 :(得分:1)

<?php

$text = "The dog is saying wooff wooff wooff wooff but he should say bark bark bark bark not wooff wooff wooff";

$newText = preg_replace_callback('|([a-zA-Z0-9]+)(\s\1)*|',function($matches){
                $same_strings = explode(" ",$matches[0]);
                return $same_strings[0] . count($same_strings);
            },$text);


echo "Old String: ",$text,"<br/>";
echo "New String: ",$newText;

输出

Old String: The dog is saying wooff wooff wooff wooff but he should say bark bark bark bark not wooff wooff wooff
New String: The1 dog1 is1 saying1 wooff4 but1 he1 should1 say1 bark4 not1 wooff3

如果您不希望发现只出现一次的单词,则可以按以下方式修改回调函数-

<?php

$text = "The dog is saying wooff wooff wooff wooff but he should say bark bark bark bark not wooff wooff wooff";

$newText = preg_replace_callback('|([a-zA-Z0-9]+)(\s\1)*|',function($matches){
                $same_strings = explode(" ",$matches[0]);
                if(count($same_strings) === 1){
                    return $matches[0];
                }
                return $same_strings[0] . count($same_strings);
            },$text);


echo "Old String: ",$text,"<br/>";
echo "New String: ",$newText;

输出

Old String: The dog is saying wooff wooff wooff wooff but he should say bark bark bark bark not wooff wooff wooff
New String: The dog is saying wooff4 but he should say bark4 not wooff3

答案 1 :(得分:0)

您可以使用preg_match_all()foreach解决此问题。
入门:

// Your string and the word you are searching
$str = "The dog is saying wooff wooff wooff wooff but he should say bark bark bark bark not wooff wooff wooff";
$search = 'wooff';

现在替换:

// Get the duplicates
preg_match_all('/(' . $search . '[\s]?){2,}/', $str, $duplicates);

// Foreach duplicates, replace them with the number of occurence of the search word in themselves
$new_str = $str;
foreach ($duplicates[0] as $dup) {
    $count = substr_count($dup, $search);
    $new_str = str_replace($dup, $search . $count . ' ', $new_str);
}
$new_str = trim($new_str);

输出:

echo $new_str;
// The dog is saying wooff4 but he should say bark bark bark bark not wooff3