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

Link to comment
Share on other sites

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.