Basically, preg_match
would do just that:
$count = 0;
foreach($_POST as $k => $v)
{
if (preg_match('/\bchap1[^\d]{0,1}/', $k)) ++$count;
}
How the pattern works:
\b
: a word-boundary. matcheschap1
, but notschap
, it can't be part of a bigger stringchap1
: matches a literal string (because it's preceded by\b
, this literal can't be preceded by a char, but it can be the beginning of a string, for example[^\d]{0,1}
: Matches anything except numbers zero or one times. sochap10
is not a match, butchap1e
is
To deal with all of these "chapters" at once, try this:
$count = array();
foreach($_POST as $k => $v)
{
if (preg_match('/\bchap(\d+)(.*)/', $k, $match))
{
$match[2] = $match[2] ? $match[2] : 'empty';//default value
if (!isset($count[$match[1]])) $count[$match[1]] = array();
$count[$match[1]][] = $match[2];
}
}
Now this pattern is a bit more complex, but not much
\bchap
: same as before, wourd boundary + literal(\d+)
: Match AND GROUP all numbers (one or more, no numbers aren't accepted). We use this group as key later on ($match[1]
)(.*)
: match and group the rest of the string. If there's nothing there, that's OK. If you don't want to match keys likechap1
, and require something after the digits, replace the*
asterisk with a plus sign
Now, I've turned the $count
variable into an array, that will look like this:
array('1' => array('e1', 'a3'),
'10'=> array('s3')
);
When $_POST
looks something like this:
array(
chap1e1 => ?,
chap1a3 => ?,
chap10s3=> ?
)
What you do with the values is up to you. One thing you could do is to group the key-value pairs per "chapter"
$count = array();
foreach($_POST as $k => $v)
{
if (preg_match('/\bchap(\d+)/', $k, $match))
{
if (!isset($count[$match[1]])) $count[$match[1]] = array();
$count[$match[1]][$k] = $v;//$match[1] == chap -> array with full post key->value pairs
}
}
Note that, if this is a viable solution for you, it's not a bad idea to simplify the expression (because regex's are best kept simple), and just omit the (.*)
at the end.
With the code above, to get the count of any "chap\d" param, simply use:
echo 'count 1: ', isset($count[1]) ? count($count[1]) : 0, PHP_EOL;