dongqu5650
2015-06-06 10:06
浏览 79
已采纳

使用正则表达式删除字符串中的字符串

I would like to remove a part of a string like in the example below (with a regex and preg_replace) :

abcd,{{any_word |same_word_but_to_keep}},efg...

Result should be :

abcd,{{same_word_but_to_keep}},efg...

Any idea?


Another example :

Bellevue,Bergouey |Bergouey(tokeep),Bourdious

Results should be :

Bellevue,Bergouey,Bourdious

Thanks a lot!!

图片转代码服务由CSDN问答提供 功能建议

我想删除字符串的一部分,如下例所示(使用正则表达式和preg_replace):< / p>

  abcd,{{any_word | same_word_but_to_keep}},efg ... 
   
 
 

结果应为:

  abcd,{{same_word_but_to_keep}},efg ... 
   
 
 

任何想法?


另一个例子:

  Bellevue,Bergouey | Bergouey(tokeep),Bourdious 
   \  n 
 

结果应为:

  Bellevue,Bergouey,Bourdious 
   \  n 
 

非常感谢!!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dounao4179 2015-06-06 12:26
    已采纳

    You could use the following regex:

    $str = 'Bellevue,Bergouey |Bergouey,Bourdious';
    $str = preg_replace('~(\w+)\s*\|(\1)~', '$2', $str);
    echo $str; //=> "Bellevue,Bergouey,Bourdious"
    
    点赞 打赏 评论
  • doutuohan6606 2015-06-06 10:12

    Try:

    preg_match_all("/\|(.*?) /", $your_string, $matches);
    foreach ($matches[1] as $match) {
        $your_string = preg_replace("/([^\|]|^)$match/", "", $your_string);
    }
    $your_string = preg_replace("/\|/", "", $your_string);
    

    How it works

    • preg_match_all("/\|(.*?) /", $your_string, $matches) Gets all the words following |
    • preg_replace("/([^\|]|^)$match/", "", $your_string) Removes all occurrences of the match not preceded by | and accounts for if the matching word is at the start of the string with |^
    • preg_replace("/\|/", "", $your_string) Removes all occurances of | from the string
    点赞 打赏 评论
  • duanbi6522 2015-06-06 12:04

    I'd do:

    preg_replace('/(\w+),(\w+)\s*\|\2,(.+)/', "$1,$2,$3", $string);
    

    Explanation:

      (\w+) : group 1, a word
      ,     : a comma
      (\w+) : group 2, a word
      \s*   : white spaces, optional
      \|    : a pipe character
      \2    : back reference to group 2
      ,     : a comma
      (.+)  : rest of the string
    
    点赞 打赏 评论
  • duanjiancong4860 2015-06-06 12:26

    Finally I found a solution without a regex, it works perfectly :

    $mystring="Arance,la Campagne,Gouze |Gouze,Lendresse";
    $tmp="";
    $words=explode(",",$mystring);
    foreach($words as $word){
        if(strpos($word,"|")){
                $l=explode("|",$word);
                $tmp=$tmp.$l[1].",";
        }else{$tmp=$tmp.$word.",";}
    }
    $mystring=$tmp;
    
    点赞 打赏 评论

相关推荐 更多相似问题