Regex: remove last character before .

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
pezkingrich
Forum Newbie
Posts: 1
Joined: Sat Apr 07, 2012 9:16 am

Regex: remove last character before .

Post by pezkingrich »

Hi all,

I have been lurking on these forums for a while and today I am making my first post as this regex stuff has really been driving me crazy :banghead: !

I need a regex expression that will determine the last number before the decimal point (.) and remove it.

Example: I have a list of file names in a directory such as:
12345678.1
12345.1

By removing the last digit before the 1 I expect these results:
12345678.1 = 1234567.1
12345.1 = 1234.1

I have tried ([A-Z^\.]{1,3}). but it is giving me errors.

Any ideas? Thank you in advance!!

pezkingrich
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Regex: remove last character before .

Post by McInfo »

Code: Select all

$str = preg_replace('/\d\./', '.', $str, 1);
or

Code: Select all

$p = strpos($str, '.');
if ($p > 0 && ctype_digit(substr($str, $p - 1, 1))) {
    $str = substr($str, 0, $p - 1).substr($str, $p);
}
Both solutions do the following transformations:

Code: Select all

'12345678.1' => '1234567.1',
'12345.1' => '1234.1'
'.1' => '.1'
'1.' => '.'
'.' => '.'
'1' => '1'
'1a.' => '1a.'
'1.1.1' => '.1.1'
'' => ''
Post Reply