1
text left - text right

How to swap right to left using php? str pos is not so good because the pattern is not always fix. It could be somethingleft-somethingright or more left text here - right

The result that I want should look like text right - text left

tried explode() but it isn't always single character at the left or right side.

6
  • Instead of considering delimiter as "-", you can consider the delimiter as " - " (notice the spaces). Commented Sep 20, 2014 at 16:01
  • @Krumia sometime it's with space but sometime is has no space.. Commented Sep 20, 2014 at 16:04
  • What code have you tried? Commented Sep 20, 2014 at 16:05
  • @user3791372 explode() but there isn't only single char at left or right Commented Sep 20, 2014 at 16:05
  • please update the question with the code you've tried Commented Sep 20, 2014 at 16:07

3 Answers 3

6

Simply can use explode(). Example here

$str = "text left - text right";
$exp = explode('-', $str);
$newStr = trim($exp[1]) . ' - ' . trim($exp[0]);
echo $newStr;
Sign up to request clarification or add additional context in comments.

Comments

1
echo trim( implode(' - ', array_reverse(explode('-', 'text left - text right'))));

1 Comment

It's a messy one liner but great for ability to use multiple delimiters
0
$strArr = preg_split(' - ','text left - text right');
$newStr = $strArr[1] . ' - ' . $strArr[0];

Split the string using the pattern ' - '. Then concatenate a new string by placing the right value $strArr[0] at the beginning of the concatenated string followed by the ' - ' pattern and finally the first half of the string $strArr[0].

2 Comments

A simple explode will suffice, but until he pastes code, I'm not going to spoon feed him
explode() might not see the spaces

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.