Log in

View Full Version : String Validation: RegEx maybe?



JBottero
09-01-2009, 05:00 AM
I have an odd input string I need to validate. Something like this:

integer ... integer|integer|integer

A string of integers. If more than one, seperated by "|"

A regex maybe? Other ideas?

JasonDFR
09-01-2009, 05:14 AM
Post a couple examples of these strings. And unless it is clear by looking at the string, list any requirements for a valid string.

It sounds like you want to only allow integers and the pipe | symbol, with each integer separated by a pipe. Is that right? How many digits can each integer contain?

prasanthmj
09-01-2009, 05:58 AM
a simple one:
^[\d\|]*$

it allows:
|||||

forum_amnesiac
09-01-2009, 06:59 AM
To check each value is an integer you could use the explode() function to get the separate elements and then check each of those.

You can check that each is an integer using the is_int() function.

This way you can find which specific elements are not an integer.

The regex posted by prasanthmj does exactly what you asked, checks the entire string and ensures that it is only integers separated by a "|", if that is what you want to do then use his answer.

However, if you want to find the 'offending' part(s) of the string then you'll need to do what I've suggested.

As they say on some gameshows, 'the choice is yours'.

JasonDFR
09-01-2009, 07:10 AM
Actually that regex does not ensure that integers are separated by |.


<?php

$var = '|11|||22|33|';
//$var = '||||||||||||||';
// $var = '1|7|77|88|99|4|4||||';

var_dump(preg_match('/^[\d\|]*$/', $var));

exit;

All the above match that regex. I think we need more information about the string and the requirements for validation.

forum_amnesiac
09-01-2009, 08:40 AM
I agree that the regular expression previously shown doesn't work properly.

I must admit to not checking it properly.

I do believe that this expression does not allow the cases that JasonDFR has shown.

^([\d]+[\|])*$

I have to point out however that the input string must terminate with a "|" for this regex to work.


(preg_match('/^([\d]+[|])*$/im', $var))

JasonDFR
09-01-2009, 10:32 AM
<?php

$regex = '/^(\d{1,5}\|)+\d{1,5}$/';

$var = '12|45|40005|5'; // matches
$var = '12|45|400505|5'; // does not match
$var = '|12|45|400505|5'; // does not match
$var = '12|45|400505|5|'; // does not match
$var = '|||||'; // does not match

var_dump(preg_match($regex, $var));

exit;

If you want to only allow one digit integers, delete the {1,5} from the regex.