1

I want to truncate a string to remove anything after the last digit. For example:

GB67 7HG - I want it to truncate to GB67 7. Preferably, I would still like the space within the string.

I am unsure where to start!

Dan
  • 9,391
  • 5
  • 41
  • 73
  • try with rtrim($text, 'A..Z'); – bksi Aug 17 '14 at 20:01
  • 2
    possible duplicate of [php preg\_match return position of last match](http://stackoverflow.com/questions/23343087/php-preg-match-return-position-of-last-match) – Noy Aug 17 '14 at 20:01

3 Answers3

1

If you are sure that you have only numbers and chars, you can use rtrim to trim unnecessary chars like $text = rtrim($text, 'A..Z ');

More for this function at: http://php.net//manual/bg/function.rtrim.php

You can use regex too, but then you need some regex skills to do that.

bksi
  • 1,606
  • 1
  • 23
  • 45
1

Another solution using regular expressions

preg_match('/(.*?)(\d+)(?!.*\d)/', 'GB67 7HG', $matches);
print_r($matches);

Output:

Array
(
    [0] => GB67 7
    [1] => GB67 
    [2] => 7
)

PHP Demo | Regex Demo

hex494D49
  • 9,109
  • 3
  • 38
  • 47
0

There's probably a cleaner solution using regular expressions, but perhaps the following will help. Simply finding the index of the last digit and using substr().

$string = 'GB67 7HG';
$count = strlen($string);
$index = -1;
$i = 0;
while( $i < $count ) {
    if( ctype_digit($string[$i]) ) {
        $index = $i;
    }
    $i++;
}
if($index != -1) echo substr($string, 0, $index + 1);
Baps
  • 103
  • 10
  • Thank you @Baps, this worked perfectly, but I chose to go with the regex for simplicity sake! –  Aug 18 '14 at 17:07