Reputation:
I have a string 18-04
, I want to make it 04-18
.
I have tried doing this :
$myStr = "18-04";
$first = substr($myStr, 0, 1);
$second = substr($myStr, 3, 4);
$final = $second . '-' . $first;
But I was looking for a simpler way rather than writing 5 full lines to do something simple. Any idea?
Upvotes: 1
Views: 51
Reputation: 21489
Use regex in preg_replace()
to do this work.
$final = preg_replace("/(\d+)-(\d+)/", "$2-$1", $myStr);
Check result in demo
Upvotes: 3
Reputation: 26153
Is it shorter ? :)
echo implode('-',array_reverse(explode('-',$myStr)));
Upvotes: 3
Reputation: 1341
you can use the following:
$myStr = "18-04";
$chuncks = explode("-",$myStr);
$final = $chuncks[1]. '-' . $chuncks[0];
Upvotes: 0