简体   繁体   English

替换PHP中的重复字符串

[英]Replacing repeated string in php

I got a string that sometime will have instance of 我有一个字符串,有时会有

This is Hello World Hello Thanks

Notice that Hello was repeat twice, I would like to replace the first "occurence" of Hello and Make it as 注意,Hello重复了两次,我想替换Hello的第一个“出现次数”,并将其设置为

This is World Hello Thanks

Is there a way I can check if there is a word is repeat twice, and to remove the first occurence and get the final string. 有没有一种方法可以检查是否有一个单词重复两次,并删除第一个出现的单词并获得最后一个字符串。

The only I could think of is using explode, and get each word by delimiter "white space". 我唯一想到的是使用explode,并通过定界符“空白”获得每个单词。

And then I not sure how to proceed on like counting occurance and removing the repeated word. 然后我不确定如何继续进行计数和删除重复的单词之类的操作。

Thanks for helping 感谢您的帮助

As per this question: Using str_replace so that it only acts on the first match? 按照这个问题: 使用str_replace使其仅在第一个匹配项上起作用?

$str = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $str, 1); // outputs '123def abcdef abcdef'

So you could use: 因此,您可以使用:

preg_replace('#Hello#', '', $input, 1)

To count the amount of times if Hello appears, see http://php.net/manual/en/function.substr-count.php 要计算出现Hello的次数,请参见http://php.net/manual/en/function.substr-count.php

$count = substr_count($input, 'Hello'); $ count = substr_count($ input,'Hello');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM