php remove everything in the string, keep the last digits
I have values like below:
$var1 = car-123-244343
$var2 = boat-2-1
$var3 = plane-311-23
I need to remove everything and keep the last digit/ditgits after the second hyphen
Expecting values:
244343
1
开发者_JAVA技巧23
This is what I've got
$stripped = preg_replace('^[a-z]+[-]$', '', 'car-123-244343');
I got a big red error No ending delimiter '^' found
Without regex:
$var1 = substr($var1, strrpos($var1, '-') + 1);
What this does is the same as:
$pos = strrpos($var1, '-') + 1
takes the last postion of'-'
and adds1
for starting at the next charactersubstr($var, $pos)
takes the$var
and returns the substring starting in$pos
.
I think is less expensive than using regex.
Edit:
As pointed below by konforce, if you are not sure which all the strings have that format, you have to verify it.
this function will work:
function foo($value)
{
$split = explode('-', $value);
return $split[count($split)-1];
}
Here is a fun version with explode:
list($vehicle, $no1, $no2) = explode('-', $data);
First, that error means your regex needs to be enclosed in delimiters (below I use the classic /
).
Second, I would rewrite your regex to this:
$stripped = preg_replace('/.+?(\d+)$/', '$1', 'car-123-244343');
If you can operate on the assumption that what comes after the last -
is always a number, the other solutions also work.
With regex:
$endnumber = preg_replace('/.*[^0-9]/', '', $input);
Remove everything up till, and including, the last non-digit.
精彩评论