Cristian
Cristian

Reputation: 7145

Remove everything after character if followed by number

Sorry for the complex title!

Say for example I have the following string:

package-name-1.0.5.00124.4

I want to split this string so that i just have 'package-name'.

At the moment I'm using the following code, which doesn't work if the package name has a dash:

list ($var) = explode ("-", $var);

I need to explode the string if the dash is followed by numbers, something like the following:

list ($var) = explode ("-[0-9]", $var);

I'm no good with Regex so that's why I'm here, thanks in advance everyone.

Upvotes: 0

Views: 226

Answers (1)

Jon
Jon

Reputation: 437336

There are a couple of ways you could choose to go about this. One would be preg_replace, replacing a trailing dash plus numbers-and-dots with the empty string:

$name = preg_replace('/-[0-9.]+$/', '', $var);

Another would be to use rtrim to do the same:

$name = rtrim($var, '0123456789.-');

See it in action.

Upvotes: 2

Related Questions