Hashey100
Hashey100

Reputation: 984

Regex not matching correctly?

I am trying to search for a subject for a match to the regular expression given in the pattern but it is not working correctly. I want to match a number/10 then a postcode

for example if the string is "hello 3/10 HU2" i want the preg_match function to match the 3 and the postcode and it needs to be in that order

the strange thing is when i try the preg_match in the opposite order so HU2 3/10 it works but when i change the code around it does not recognize the value 3.

Any help would be appreciated

the code below works for the order HU2 3/10 but i need it in the opposite order

<?php

    preg_match('/([A-Za-z]{1,2}[0-9][A-Za-z0-9]?) ([0-9]{1,2})/', "HU2 3/10", $matches);    

    echo $matches[1];
    echo "<br>";
    echo $matches[2];


?>

Upvotes: 0

Views: 113

Answers (3)

UT-Fan-05
UT-Fan-05

Reputation: 426

Here's a regex that I've tried with various strings and seems to work:

Regex: ([^ ]+) *(\d*\/10) *([A-Za-z0-9]+) *(.*)

Test strings:
1) hello 3/10 HU2
2) test this regex 3/10 HU2 param1 param2
3) testid 33323/10 HU2332GG param1 param2

I'm not quite sure on all the requirements but this can be the basis for your regex. You can also use the online regex tool to quickly verify your regex here: http://www.regexplanet.com/advanced/java/index.html

Upvotes: 0

Otaia
Otaia

Reputation: 451

You're not matching the /10, are you?

(\d{1,2})/10 ([A-Za-z]{1,2}\d\w?)

matches

hello 3/10 HU2

group 1: 3
group 2: HU2

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44259

If you change it around, you have to include the /10 in the pattern. Note that you can change the delimiters so that you don't have to escape the forward slash:

preg_match('~([0-9]{1,2})/10 ([A-Za-z]{1,2}[0-9][A-Za-z0-9]?)~', "3/10 HU2", $matches);

The [0-9] can be replaced with \d. Also, if 10 is a variable number, that's easy to take into account, too:

preg_match('~(\d{1,2})/\d+ ([A-Za-z]{1,2}\d[A-Za-z0-9]?)~', "3/10 HU2", $matches);

As a final optimisation, the use of the i modifiers, let's you leave out half of the letters (it makes the pattern case-insensitive):

preg_match('~(\d{1,2})/\d+ ([A-Z]{1,2}\d[A-Z0-9]?)~i', "3/10 HU2", $matches);

Upvotes: 1

Related Questions