Page 1 of 1

need some help with regular expression

Posted: Thu Sep 04, 2003 7:11 am
by yaron
Hello all,
I've been dealing for something for an hour with no success and it driving me crazy.
my perl is too weak .
here is my problem:
I have a string wich may or may not contain numbers.
from that string I need to get a substring as followed:
from the second digit take 4 steps back.
example 1:
string-hr-0223-bla
result:
hr-02

example 2:
yd-99string
result:
yd-99

I know it's not so hard but it's driving me NUTS!

Posted: Thu Sep 04, 2003 7:32 am
by volka

Code: Select all

<?php
$pattern = '!(.{3}\d{2})!';

$subjects = array(
	'string-hr-0223-bla',
	'yd-99string'
);

foreach($subjects as $sub)
{
	preg_match($pattern, $sub, $match);
	print_r($match);
}
?>
or can it be something like string-1a2 -> g-1a2, too?

Posted: Thu Sep 04, 2003 7:44 am
by yaron
works on 95% of the case.
when the string is : string-hr-97 i.e. the digits are last there is no match in preg_match

Posted: Thu Sep 04, 2003 7:48 am
by yaron
sorry, my bad
works 100%
thank you!!

Posted: Thu Sep 04, 2003 3:44 pm
by m3rajk
you might want to adjust it.

if the string can be say "adfsdfsd-978sdfsadfsdfas-9087" the you want to change the pattern to /.*(.{3}\d{2}).*/

Posted: Thu Sep 04, 2003 5:42 pm
by volka
that doesn't matter

Code: Select all

<?php
$pattern = '!(.{3}\d{2})!';

$subjects = array(
   'string-hr-0223-bla',
   'yd-99string',
   'adfsdfsd-978sdfsadfsdfas-9087'
);

foreach($subjects as $sub)
{
   preg_match($pattern, $sub, $match);
   print_r($match);
}
?>
Array
(
[0] => hr-02
[1] => hr-02
)
Array
(
[0] => yd-99
[1] => yd-99
)
Array
(
[0] => sd-97
[1] => sd-97
)
unless you use ^ resp. $ it doesn't matter where in subject the pattern matches, first match->done.

Posted: Fri Sep 05, 2003 12:10 pm
by m3rajk
are you sure? i thought without a specifically set limit that preg_match would act like perl and look for as many matches as it can make, thus in the example i gave, the second set would also be returned since you are CAPTURING.

Posted: Fri Sep 05, 2003 5:23 pm
by volka
I'm sure because the second block is the output of the script ;)
You mean preg_match_all()