Hello I have a scenario that, in textbox I can enter string like
"1,2,3" this would be allowed.
but if someone enters,
"1,2,,3" this would not be allowed.
allowed multiple commas but not like above.
Thanks in advance
Hello I have a scenario that, in textbox I can enter string like
"1,2,3" this would be allowed.
but if someone enters,
"1,2,,3" this would not be allowed.
allowed multiple commas but not like above.
Thanks in advance
Try this reg-ex:
/^\d(?:,\d)*$/
Explanation:
/ # delimiter
^ # match the beginning of the string
\d # match a digit
(?: # open a non-capturing group
, # match a comma
\d # match a digit
) # close the group
* # match the previous group zero or more times
$ # match the end of the string
/ # delimiter
If you allow multi-digit numbers, then change \d to \d+.
Try this,
if(in_array("", explode(',',$str)))
{
// validation fail
}
You can simply do a regex test to check. If the only thing you want to prevent is duplicate commas:
if (preg_match('/,,/', $myString)) {
// not allowed... do something about it
}
If you want to limit it to only a pattern of numbers, separated by commas, swap the regex pattern for '/^([0-9]+,?)+$/'
, which only 1 or more numbers, optionally followed by a decimal, with that pattern repeated any number of times (but must have at least one number). Also, flip the conditional around, so:
if (!preg_match('/^([0-9]+,?)+$/', $myString)) {
// not allowed... do something about it
}
If you want something a little simpler, doing this will also solve it (and be a little more efficient, if all you want is to test for multiple commas together):
if (strpos($myString, ',,') !== false) {
// not allowed... do something about it
}
Try This:
if (strpos($input_string,',,') == true) {
echo 'Invalid string';
}
You can detect this using (preg_match will work too of course):
if(strpos($your_string, ',,') !== false) {
echo "Invalid"
}
Do you also need to detect leading or trailing commas?
Also keep in mind if validation is not really necessary you can simply "fix" the input by using explode
and filtering out empty string elements, and then implode
array:
$your_string = implode(',', array_filter(explode(',', $your_string), function ($i) {
return $i !== '';
}));
use the strpos()
function for your above requirement
if (strpos($youstring,',,') == false) {
echo 'String not found';
}
else
{
echo 'String is found';
}
You can use stristr function to fix this
if(stristr ($Array,',,'))
echo 'Flase';
else
// do something