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

remove a string inside a string with regex

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

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

结果应该是:

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

有什么想法吗?


另一个例子:

Bellevue,Bergouey |Bergouey(tokeep),Bourdious

结果应该是:

Bellevue,Bergouey,Bourdious

非常感谢!!

尝试:

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

工作原理

  • preg_match_all("/\|(.*?) /", $your_string, $matches) 获取 |
  • 之后的所有单词
  • preg_replace("/([^\|]|^)$match/", "", $your_string) 删除所有不以 | 开头的匹配项,并说明匹配词是否位于 |^
  • 字符串的开头
  • preg_replace("/\|/", "", $your_string) 从字符串
  • 中删除所有出现的 |

我愿意:

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

解释:

  (\w+) : group 1, a word
  ,     : a comma
  (\w+) : group 2, a word
  \s*   : white spaces, optional
  \|    : a pipe character
      : back reference to group 2
  ,     : a comma
  (.+)  : rest of the string

您可以使用以下正则表达式:

$str = 'Bellevue,Bergouey |Bergouey,Bourdious';
$str = preg_replace('~(\w+)\s*\|()~', '', $str);
echo $str; //=> "Bellevue,Bergouey,Bourdious"

最后我找到了一个没有正则表达式的解决方案,它工作得很好:

$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;