RegEx for PHP preg_replace swapping matches and matching multiple instances

267 views Asked by At

I'm looking for a RegEx for preg_replace in PHP for the following scenario:

  • example string "Bjerre- Jonas, Jorgensen- Silas, Wohlert- Johan, Madsen- Bo"
  • desired string "Jonas Bjerre, Silas Jorgensen, Johan Wohlert, Bo Madsen"
  • string is a csv field and double quotes are enclosures and are part of string
  • any number of occurrences may exist including none - the example clearly has 4
  • there is a consistent - to match on separating matches to be swapped

I'm a noob at PHP and RegEx and have been playing around in the cool test arena with things like preg_replace("/^\"(?<=- )/", ""$2 $1$3"", $input_lines); with horrible results. Thanks for help!

1

There are 1 answers

8
vks On BEST ANSWER
([^," -]*)\s*-\s*([^," ]*)

Try this.See demo.

http://regex101.com/r/hI0qP0/20

$re = "/([^\", -]*)\\s*-\\s*([^,\" ]*)/m"; 
$str = "\"Bjerre- Jonas, Jorgensen- Silas, Wohlert- Johan, Madsen- Bo\""; 
$subst = "$2 $1"; 

$result = preg_replace($re, $subst, $str);