Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Regex - optional part

Tags:

regex

php

I have a problem involving PHP and regex.

I have some files and need to capture some of the names. But there's one part that are not in all.

Example files:
D.SAE.IND.001.TME.BR.SER.20120729
D.SUI.IND.003.TMC.GER.TOT.201206
D.SAE.LIS.008.AGE.APS.SER.45D.20120713

Note that the last file has a part ("45D") that is optional.
I need to get every group. I was using the following regex:

preg_match('/D\.(?P<font>[\w]*)\.(?P<tipo>[\w]*)\.(?P<numberLevel>[\d]*)\.(?P<indicator>[\w]*)\.(?P<nameLevel>[\w]*)\.(?P<group>[\w]*)\.(?P<id>[\d]*)/i', $arrInput , $result);

The problem is that optional part (eg the latest file - "45D").
I need this result:

D.SAE.IND.001.TME.BR.SER.20120729
$result['fonte'] = 'SAE'
$result['tipo'] = 'IND'
$result['numberLevel'] = '001'
$result['indicator'] = 'TME'
$result['nameLevel'] = 'BR'
$result['group'] = 'SER'
$result['op'] = ''
$result['id'] = '20120729'

D.SAE.LIS.008.AGE.APS.SER.45D.20120713
$result['fonte'] = 'SAE'
$result['tipo'] = 'LIS'
$result['numberLevel'] = '008'
$result['indicator'] = 'AGE'
$result['nameLevel'] = 'APS'
$result['group'] = 'SER'
$result['op'] = '45D'
$result['id'] = '20120713'

Thank you in advance for help.

like image 650
NakaBr Avatar asked Dec 18 '25 18:12

NakaBr


2 Answers

Why don't you just use explode('.', $string)?

You can count the array to see the number of entries. If it's 7, you know you are missing the optional string.

like image 95
Explosion Pills Avatar answered Dec 21 '25 06:12

Explosion Pills


This works for me:

/D\.(?P<font>[\w]*)\.(?P<tipo>[\w]*)\.(?P<numberLevel>[\d]*)\.(?P<indicator>[\w]*)\.(?P<nameLevel>[\w]*)\.(?P<group>[\w]*)\.(?:(?P<op>.*)\.)?(?P<id>[\d]*)/i

The key is adding:

(?:(?P<op>.*)\.)?

Before the id group.

Edit: Added the ?: to make the grouping non-capturing.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!