-1

I have to take out some part of a string and append it to the end. I could do it with basic str_replace() and the . operator. However, the part I want to extract is not constant. So, I need to get and store it somewhere before I can append it. How should I proceed?

Here is an example:

$initial = 'I like apples and mangoes same as you.';
$final = 'I like same as you. apples and mangoes.';

In this case, I have moved everything between like and same to the end.

iKnowNothing
  • 175
  • 11
  • 2
    What is not constant? Can you provide a second example? – Paolo Aug 12 '18 at 19:11
  • Did you try preg_replace ? – NobbyNobbs Aug 12 '18 at 19:12
  • This is simply too broad as it stands. The example you have given can be manipulated as you require in your desired output, but it will only ever do that one thing matching that exact/precise example. I suspect you either need a more generic check to find other things, or if it truly is just this one thing then you can do a simple `IF` and match the exact words. – James Aug 12 '18 at 20:00

1 Answers1

1

Use a regular expression to capture the part that comes between like and same, while also capturing same and everything that comes after it in another group. Then, replace with the second group followed by the first group, switching their positions. No intermediate variable needed:

$initial = 'I like apples and mangoes same as you.';
$final = preg_replace('/(?<=like)(.+)( same.+$)/', '$2$1', $initial);
print($final);

Output:

I like same as you. apples and mangoes
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320