Julien
Julien

Reputation: 4163

remove a string inside a string with regex

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!!

Upvotes: 0

Views: 62

Answers (4)

Julien
Julien

Reputation: 4163

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;

Upvotes: 0

hwnd
hwnd

Reputation: 70722

You could use the following regex:

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

Upvotes: 2

Toto
Toto

Reputation: 91385

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

Upvotes: 1

thodic
thodic

Reputation: 2259

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

Upvotes: 1

Related Questions