Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exploding a string, only at the last occurrence of the explode match

Tags:

php

explode

I'm trying to explode a string, but I need it to explode only at the last 'and' instead of every 'and'. Is there a way to do that?

<?php

$string = "one and two and three and four and five";
$string = explode(" and ", $string);

print_r($string);

?>

Result:

Array ( [0] => one [1] => two [2] => three [3] => four [4] => five )

Need Result:

Array ( [0] => one and two and three and four [1] => five )

like image 357
frosty Avatar asked Jan 23 '26 05:01

frosty


1 Answers

This seems easy enough to do using just basic string functions.

$x = strrpos($string, ' and ');
$s2 = array(substr($string, 0, $x), substr($string, $x + 5));
like image 140
Don't Panic Avatar answered Jan 24 '26 19:01

Don't Panic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!