用它的出现次数替换子字符串

Replace sub string with number of it's occurrences

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

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

$newText = preg_replace('!\wooff+', 'wooff{$total}', $text);


结果应该是:

$newText = "The dog is saying wooff4 but he should say 
bark bark bark bark not 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)*|',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)*|',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

您可以使用 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