Jump to content

[SOLVED] matching 999 or 1,123 number formats


daydreamer

Recommended Posts

Hello.

 

I am trying to match either a 3 digit number or a 4 digit in this format: "1,123".

 

This is what I have:

 

<?php
preg_match("~(\d?,?\d\d\d)~i", $searchhere, $matches);
?>

 

It matches 3 digit numbers fine. But something like "1,123" will return "123".

 

Whats up with this?!

 

Link to comment
Share on other sites

yeh that wasnt the full code thats the part where I thought it was.

 

I had something similar to:

<?php
preg_match("~.*(\d?,?\d\d\d)~i", $searchhere, $matches);
?>

 

I think the .* was matching some of the numbers so it wasnt returning them all.

 

Thanks for the test!

Link to comment
Share on other sites

In it's rawest form:

 

$str = 'blah 1,234 more blah';
preg_match('#(?:\d,)?\d{3}#', $str, $match);
echo $match[0];

 

However, if it encounters a number like 1234, it will match 123 (which I assume is not desirable). So perhaps we can also make use of a conditional and \D:

 

$str = 'blah 1,234 more blah';
if(preg_match('#\D(?:\d,)?\d{3}\D#', $str, $match)){
    echo $match[0];
} else {
    echo 'No proper format found.';
}

 

But I suppose this highly depends on the circumstances of where the 3 or 4 digit number is situated within the string. If the numbers are at the beginning of the string, the initial \D will throw it off. If that's the case, the pattern could be amended to:

 

#(^|\D)(?:\d,)?\d{3}\D#

 

In either case, I noticed you made use of the 'i' modifier, which is not usable in your example, as this is case insensative.. but since you are using digits and commas, the 'i' doesn't perform anything.

 

EDIT - An even more refined method based off the last one:

if(preg_match('#(?:^|\D)\K(?:\d,)?\d{3}(?=\D|$)#', $str, $match)){

 

This will now match those numbers at the start or at the end of a string.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.