Quick Regular Expression Question

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
JessieArr
Forum Newbie
Posts: 2
Joined: Sat Mar 27, 2010 2:29 pm

Quick Regular Expression Question

Post by JessieArr »

Greetings all!

I am looking to parse a regular expression of the following format:
[number with 1-5 characters][colon] ([number with 1-5 characters][semicolon][number with 1-2 characters][colon])* [colon]

ex: 16231:484;4:499;3::

I've been using this call to ereg: ereg("^([0-9]{1,5}):(([0-9]{1,5});([0-9]{1,2}):)*:", $q, $regs);

But my output isn't what I'm expecting, it seems to alternate between storing the whole string in the array, then the next variable. Is this due to my regular expression being incorrect, or am I simply using the function wrong? This is my first time using regular expressions, and I'm also kind of a PHP noob, just hoping someone can point me in the direction of my problem.

Sample output for: 16231:484;4::
$regs[0] = 16231:484;4::
$regs[1] = 16231
$regs[2] = 484;4:
$regs[3] = 484
$regs[4] = 4

I could just skip alternate array elements and hardcode the end, but that feels like too much of a hack and I suspect there's a better way. Thanks in advance for your responses!
User avatar
Zlobcho
Forum Newbie
Posts: 18
Joined: Sun Jun 21, 2009 7:57 pm

Re: Quick Regular Expression Question

Post by Zlobcho »

Hi,

Your question is for RegEx forum.

Below is one quick implementation with pcre:

Code: Select all

<?php

$data = '1431:141;5::';
preg_match('/^(\d{1,5})\:(\d{1,5})\;(\d{1,2})\:.*(?:\:)$/', $data, $matches);
var_dump($matches);

?>
Output:

[syntax]
array(4) {
[0]=>
string(12) "1431:141;5::"
[1]=>
string(4) "1431"
[2]=>
string(3) "141"
[3]=>
string(1) "5"
}
[/syntax]


Hope this helps. :)
JessieArr
Forum Newbie
Posts: 2
Joined: Sat Mar 27, 2010 2:29 pm

Re: Quick Regular Expression Question

Post by JessieArr »

Problem solved. That wasn't exactly what I was looking for, but it got me looking in the right direction: at the other regex functions which led to a solution. I ended up just using preg_split to slice the string into array elements, each of which was a variable I needed.

$regs = preg_split("/:|;/", $q); //Slices string into array elements delimited with either ':' or ';'

Works great and I've got the database queries working correctly now. Thanks for the help!
Post Reply