Mojtaba Reyhani
Mojtaba Reyhani

Reputation: 457

How can remove the numberic suffix in php?

For example, if I want to get rid of the repeating numeric suffix from the end of an expression like this: some_text_here_1
Or like this:
some_text_here_1_5
and I want finally receive something like this:
some_text_here

What's the best and flexible solution?

Upvotes: 0

Views: 1002

Answers (4)

Andreas
Andreas

Reputation: 23958

Updated to fix more than one suffix

Strrpos is far better than regex on such a simple string problem.

$str = "some_text_here_13_15";

While(is_numeric(substr($str, strrpos($str, "_")+1))){
    $str = substr($str,0 , strrpos($str, "_"));
}
Echo $str;

Strrpos finds the last "_" in str and if it's numeric remove it.
https://3v4l.org/OTdb9

Just to give you an idea of what I mean with regex not being a good solution on this here is the performance.
Regex:
https://3v4l.org/Tu8o2/perf#output
0.027 seconds for 100 runs.

My code with added numeric check:
https://3v4l.org/dkAqA/perf#output
0.003 seconds for 100 runs.
This new code performs even better than before oddly enough, regex is very slow. Trust me on that

You be the judge on what is best.

Upvotes: 2

Ivo P
Ivo P

Reputation: 1712

$reg = '#_\d+$#';
$replace = '';
echo preg_replace($reg, $replace, $string);

This would do

abc_def_ghi_123 >  abc_def_ghi
abc_def_1       >  abc_def
abc_def_ghi     > abc_def_ghi
abd_def_        >  abc_def_
abc_123_def     > abd_123_def

in case of abd_def_123_345 > abc_def one could change the line

$reg = '#(?:_\d+)+$#';

Upvotes: 1

dave
dave

Reputation: 64677

$newString = preg_replace("/_?\d+$/","",$oldString);

It is using regex to match an optional underscore (_?) followed by one or more digits (\d+), but only if they are the last characters in the string ($) and replacing them with the empty string.

To capture unlimited _ numbers, just wrap the whole regex (except the $) in a capture group and put a + after it:

$newString = preg_replace("/(_?\d+)+$/","",$oldString);

If you only want to remove a numberic suffix if it is after an underscore (e.g. you want some_text_here14 to not be changed, but some_text_here_14 to be changed), then it should be:

$newString = preg_replace("/(_\d+)+$/","",$oldString);

Upvotes: 3

Obsidian Age
Obsidian Age

Reputation: 42354

First you'll want to do a preg_replace() in order to remove all digits by using the regex /\d+/. Then you'll also want to trim any underscores from the right using rtrim(), providing _ as the second parameter.

I've combined the two in the following example:

$string = "some_text_here_1";
echo rtrim(preg_replace('/\d+/', '', $string), '_'); // some_text_here

I've also created an example of this at 3v4l here.

Hope this helps! :)

Upvotes: 1

Related Questions