-1

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

medk
  • 9,233
  • 18
  • 57
  • 79
  • 1
    Since the end is dynamic, it is not possible with trim. Regex (preg_replace) would be the right way to do that. – shelly Nov 09 '20 at 09:09

3 Answers3

2

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.

Martijn
  • 15,791
  • 4
  • 36
  • 68
1

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"
Ermenegildo
  • 1,286
  • 1
  • 12
  • 19
0

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

Marwane Ezzaze
  • 1,032
  • 5
  • 11