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?
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?
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?
a simple one:
^[\d\|]*$
it allows:
|||||
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'.
Actually that regex does not ensure that integers are separated by |.
All the above match that regex. I think we need more information about the string and the requirements for validation.PHP Code:<?php
$var = '|11|||22|33|';
//$var = '||||||||||||||';
// $var = '1|7|77|88|99|4|4||||';
var_dump(preg_match('/^[\d\|]*$/', $var));
exit;
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.
PHP Code:(preg_match('/^([\d]+[|])*$/im', $var))
If you want to only allow one digit integers, delete the {1,5} from the regex.PHP Code:<?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;
Last edited by JasonDFR; 09-01-2009 at 10:41 AM.
Bookmarks