首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >删除字符串中变量的重复项?

删除字符串中变量的重复项?
EN

Stack Overflow用户
提问于 2010-11-17 18:12:53
回答 4查看 91关注 0票数 2

假设你有这样一个字符串:

代码语言:javascript
运行
复制
  $string = 'hello my name is blah blah and wats yours';

你想检查所有可能有复制品的地方..不是任何单词,而是本例中所选的单词“blah”。

代码语言:javascript
运行
复制
   $variable = 'blah';

也就是说,如果“blah”背靠背出现--删除其中一个。

我考虑将字符串拆分成一个数组,如果数组中的一个变量以相同的单词开头,则最后一个变量以相同的单词结尾,然后去掉一个变量并重新构建字符串。看起来很繁琐,所以这就是为什么我要问是否有更简单的方法。

有什么想法吗?

编辑:我刚刚意识到我没有考虑做一个简单的‘preg_match’和'blah‘。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-17 18:31:39

这样如何:

代码语言:javascript
运行
复制
$string = 'hello my name is blah blah and wats yours';
$variable = 'blah';
$string = preg_replace( '/(\b'.$variable.'\s+){2,}/' , '\1' , $string );

允许处理多个变量(例如,您可以遍历多个$variable,也可以创建它们的数组并使用单个preg_replace()调用。

或者只使用str_replace()

代码语言:javascript
运行
复制
$string = 'hello my name is blah blah and wats yours';
$variable = 'blah';
$string = str_replace( $variable.' '.$variable.' ' , $variable.' ' , $string );
票数 3
EN

Stack Overflow用户

发布于 2010-11-17 18:17:54

代码语言:javascript
运行
复制
$string = 'hello my name is blah blah and wats yours';
$search_string = 'blah';

$first_occurence = strpos($string , $search_string);

If (int preg_match($search_string , $string ) > 1) {
    echo "String found more than once!!!";

    // remove all occurences of searchstring from string excepte the first one
    $string = substr ($string, 0, $first_occurence +1) . str_replace($search_string, '', substr ($string,$first_occurence +1));
}
票数 1
EN

Stack Overflow用户

发布于 2010-11-17 18:18:46

您可以检查$variable在$string中的每个匹配项的位置,并检查几个匹配项的位置是否只是在$variable的长度上不同(可能+空格)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4203360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档