Jump to content

Switching text after minus sign


Mcod

Recommended Posts

Hi there,

 

I need some help with modifying a string.

 

I always have strings that look like:

 

This is part two - This is part one

This is part four - This is part three

 

What I need is to switch the position which is separated by space minus sign space, so it returns:

 

This is part one - This is part two

This is part three - This is part four

 

Something like:

 

$string = "this is part two - this is part one";

 

after the code I am looking for ran, it would return:

 

$newstring = "this is part one - this is part two";

 

Any ideas how this could be done so it works for everything that is separated by space minus space?

 

Thank you for your time :)

Link to comment
https://forums.phpfreaks.com/topic/253498-switching-text-after-minus-sign/
Share on other sites

Hi Mcod!

 

This regex will reverse your strings.

 

Match expression:

([^-]*?) -(.*)

 

Replace expression:

\2 - \1

 

Here is an example of preg_replace integration ($subject is your string):

$result = preg_replace('/([^-]*?) -(.*)/m', '\2 - \1', $subject);

 

Is this what you were looking for?

  • 3 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.