In PHP how to use trim() or rtrim() to remove the last space and the characters after?
Expample:
Any Address 23B
to become
Any Address
AND
Another Address 6
to become
Another Address
In PHP how to use trim() or rtrim() to remove the last space and the characters after?
Expample:
Any Address 23B
to become
Any Address
AND
Another Address 6
to become
Another Address
You cant. Trim is for spaces and tabs etc, or specified characters. What you want is more specific logic.
If you want it from the last space:
$lastSpace = strrpos($string, ' ');
$street = substr($string, 0, $lastSpace);
$number = substr($string, $lastSpace+1);
You can also implode
on space, use array_pop
to get the last value and then implode
, but array functions on string manipulation are costly compared to a substr
.
You can also use a regex to get the last values, but while it's better than array manipulation for string, you should use it as a plan B as a regex isn't the most lightweight option either.
Why don't you use a regex?
$address = 'Any Address 23B';
$matches = [];
preg_match('/(?P<street>.*) \w+$/', $address, $matches);
print_r($matches['street']); // OUTPUT: "Any Address"
in case you dont wanna use the answers above, here is one solution without regex:
$string = 'Any Address 23B';
$stringRev = explode(' ', strrev($string), 2);
echo strrev($stringRev[1]); //result: Any Address