Forum Moderators: coopster

Message Too Old, No Replies

Regular Expression

regular, expression, regular expression

         

swanweb

6:37 pm on Apr 16, 2007 (gmt 0)

10+ Year Member



I am having a mare with regular expressions...

I have some codes

AHJV1
AHJ2
AHJVS10

I need a regular expression to identify the code {code}{number} i also would like to use the number....

ANy help is appreciated

mooger35

7:54 pm on Apr 16, 2007 (gmt 0)

10+ Year Member



preg_replace [ca3.php.net] seems like a good bet for what you are looking for.

$string = "ABC123";
$number = preg_replace('/[^0-9_]/i','',$string);
$code = preg_replace('/[^a-z_]/i','',$string);

something like that?

eelixduppy

1:03 am on Apr 17, 2007 (gmt 0)



preg_match_all [us.php.net] seems to be a little more appropriate for this situation if you want to "use" the codes. This should match all of them:

$matches = array();
$pattern = "/([A-Z]+)([0-9]+)/";
preg_match_all($pattern,$string,$matches);
echo '<pre>';
print_r($matches);
echo '<pre>';

Good luck! :)

BananaFish

4:14 am on Apr 17, 2007 (gmt 0)

10+ Year Member



You can use the e modifier to evaluate the backtracked variables to populate the $code and $number variables with the appropriate data:

$dmb=preg_replace(/^([a-z]+)([0-9]+)$/ie',"\$code=\"\\1\";\$number=\\2;",$string);

BananaFish

4:16 am on Apr 17, 2007 (gmt 0)

10+ Year Member



Should be:
$dmb=preg_replace('/^([a-z]+)([0-9]+)$/ie',"\$code=\"\\1\";\$number=\\2;",$string);

swanweb

3:54 pm on Apr 17, 2007 (gmt 0)

10+ Year Member



I used the following solution:

$number = preg_replace('/[^0-9_]/i','',$name);
$code = preg_replace('/[^a-z_]/i','',$name);

However it replaces all numbers in the string, but i have realised that some of the codes contains numbers i.e.

IDHG2HG10
code = IDHG2HG
number = 10

ID2H3
code = ID2H
number = 3

I need to be able to get the number after the code only which may contain numbers :D confusing i know

BananaFish

3:05 am on Apr 19, 2007 (gmt 0)

10+ Year Member



If the number is simply the ending digits, try this:

preg_match('/^(\w+)(\d+)$/',$name,$matches);
if($matches[0]){
$code=$matches[1];
$number=$matches[2];
}
else {
$code="Not Found";
$number="Not Found";
}

swanweb

6:27 pm on Apr 21, 2007 (gmt 0)

10+ Year Member



WORKED A TREAT!