need some help with regular expression

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

need some help with regular expression

Post 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!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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?
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post 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
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post by yaron »

sorry, my bad
works 100%
thank you!!
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post 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}).*/
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I'm sure because the second block is the output of the script ;)
You mean preg_match_all()
Post Reply