0

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!

0

1 Answer 1

1
([^," -]*)\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);
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, vks! It complains if I use 'g' modifier per demo but seems to work fine without any modifiers at all.
@BartmanEH g is implicit with preg_replace(), you don't need to include it.
I added a space after the dash to match only the unique case of '- ' as follows: /([^", - ]*)\s*-\s*([^," ]*)/ and now it works for the following string with hyphenated lastname: "Reisle- Martin, Malinowski- Jay, Brant-Briscall- Aiden, Vaughan- Elliot, Dolmont- Mark" returning "Martin Reisle, Jay Malinowski, Aiden Brant-Briscall, Elliot Vaughan, Mark Dolmont"
@BartmanEH that is incorrect.` - ` inside [] forms an incorrect range.Use regex101.com/r/hI0qP0/24 instead.
Thanks again vks. I was reviewing regex101.com's explanation of how it worked and couldn't understand how my error with an incorrect range worked at all but that's the way it goes with RegEx - you can get remarkably good accidental results in some test cases but the error will be exposed in subsequent test cases or in production
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.