I have a string that looks like this: This is a sample string
and I want to separate the sting so that the first words are in one variable and the last word is in another. So:
$beginning = "This is a sample"
$lasword = "string"
How can I do that?
There are several ways to do this. One easy way (though not necessarily the most efficient) is to make an array by splitting on the spaces, remove the last one, and then stick the rest back together into a string via
explode(),array_pop(),implode()A bunch of substring operations making use of
strrpos()to find the last occurrence of the space andsubstr()orstr_split()to chop it up are likely to be more efficient, but honestly I would be more likely to use this method unless performance was really an issue.