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!
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!
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.
Another solution using regular expressions
preg_match('/(.*?)(\d+)(?!.*\d)/', 'GB67 7HG', $matches);
print_r($matches);
Output:
Array
(
[0] => GB67 7
[1] => GB67
[2] => 7
)
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);