Php 将子字符串替换为其编号';事件
我想用子字符串的出现次数替换它,例如:Php 将子字符串替换为其编号';事件,php,preg-replace,Php,Preg Replace,我想用子字符串的出现次数替换它,例如: $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 s
$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\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;
您可以使用和
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
好的,那么代码有问题吗?它会产生错误吗?它是否产生任何输出?简而言之,问题是什么?
woof-woof-bark-woof
看起来像什么?@riggsfuly-plase检查更新,我不确定preg_-replace是否有一些回调功能来显示我描述的preg-replace单词。@abracadver请检查更新again@vivek_23这正是我所想的:D!很好的工作伙伴
// 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