Forum Moderators: coopster

Message Too Old, No Replies

Need help with a regex expression

         

Crump

11:50 pm on Aug 12, 2010 (gmt 0)

10+ Year Member



I need to remove a period (.) from a line but ONLY if it is preceded by a character (A-Z).

In other words, this:

XYZ.1234

Would turn in to:

XYZ.1234

but this:

123.4567

Would simply be left alone.

Any ideas?

bedlam

12:09 am on Aug 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've already been pushing my luck with regular expressions here today, but I'll take a shot. Something like this should work:


$pattern = '/([a-zA-z]+)(\.[\d]+)/';
$replacement = '$1$3'
print preg_replace($pattern, $replacement, $subject);

-- b

bedlam

3:05 am on Aug 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Did I mention I'd been pushing my luck? Then I post a regex with a backreference to $3 when there are not three subparts to the pattern...#*!@#$%! Too eager to get off to the pub...

$pattern = '/^([a-z]+)(\.)([\d]+)$/i';
$replacement = '$1$3'
print preg_replace($pattern, $replacement, $subject);


This says–unless I've borked it again–"replace any string beginning with a series of one or more letters, followed by exactly one dot, followed by (and ending with) a series of digits, evaluated without respect to the case of the letters, with the aforementioned series of letters concatenated to the aforementioned series of digits".

-- b

rocknbil

7:34 pm on Aug 13, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



TMTOWTDI again. :-) You don't need classes for only one member in the class (digits,) but since we have a character class, you can use a not for at least the match preceding the dot.


<?php
header("content-type:text/html");
$pattern = '/^(.*[^\d])\.(\d+)$/i';
$replacement = "$1$2";
// comma intentional
$tests = array ('XYZ.1234','123.4567','12D.634','12E,123');
foreach ($tests as $t) {
print "orig: $t replacement: ";
print preg_replace($pattern, $replacement, $t) . "<br>";
}
?>


Note it's a little move forgiving due to:

but ONLY if it is preceded by a character (A-Z).


See the third array member . . . .

Crump

5:01 am on Aug 26, 2010 (gmt 0)

10+ Year Member



Thanks to everyone for your replies. The code works, however, I have hit a snag. I meant to give a better example in my first post. I need this to occur within a line.

For instance:

Blah blah blah random number 13.24 and then this ABC.123 and some other random 12.44 number

This would turn in to this:

Blah blah blah random number 13.24 and then this ABC 123 and some other random 12.44 number


Any ideas?