angry kiwi
angry kiwi

Reputation: 11485

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
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

Upvotes: 2

Views: 637

Answers (5)

BoltClock
BoltClock

Reputation: 724192

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.

Upvotes: 2

bart
bart

Reputation: 7777

With regex:

$endnumber = preg_replace('/.*[^0-9]/', '', $input);

Remove everything up till, and including, the last non-digit.

Upvotes: 1

erisco
erisco

Reputation: 14329

Here is a fun version with explode:

list($vehicle, $no1, $no2) = explode('-', $data);

Upvotes: 2

Murilo Vasconcelos
Murilo Vasconcelos

Reputation: 4827

Without regex:

$var1 = substr($var1, strrpos($var1, '-') + 1);

What this does is the same as:

  1. $pos = strrpos($var1, '-') + 1 takes the last postion of '-' and adds 1 for starting at the next character
  2. substr($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.

Upvotes: 4

Yoram de Langen
Yoram de Langen

Reputation: 5509

this function will work:

function foo($value)
{
    $split = explode('-', $value);
    return $split[count($split)-1];
}

Upvotes: 2

Related Questions