PHP strpos () function for comparing string conflicts in numbers

I use the strpos () function to find a string in the elements of an array.

    foreach($_POST as $k => $v){
    // for all types of questions of chapter 1 only
    $count = 0;
    if(strpos($k, 'chap1') !== false){
        $count++;
    }
}

I know that it only works until the keys (chap1e1, chap1m1, chap1h1), but when it comes to (chap10e1, chap10m1, chap10h1), my logic will not work on them.

Is there no way that I can distinguish between comparisons (chap1 and chap10)?

Or is there an alternative way to do this? Please give me some ideas. Thanks!

+4
source share
4 answers

Basically, it preg_matchwill do just that:

$count = 0;
foreach($_POST as $k => $v)
{
    if (preg_match('/\bchap1[^\d]{0,1}/', $k)) ++$count;
}

How the template works:

  • \b: word boundary. matches chap1, but not schap, it cannot be part of a larger string
  • chap1: ( \b, char, ,
  • [^\d]{0,1}: , , . chap10 , chap1e

"" , :

$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];
    }
}

,

  • \bchap: , , wourd + literal
  • (\d+): ( ). ($match[1])
  • (.*): . , . , chap1 - , *

$count , :

array('1' => array('e1', 'a3'),
      '10'=> array('s3')
);

$_POST :

array(
    chap1e1 => ?,
    chap1a3 => ?,
    chap10s3=> ?
)

, , . , , - ""

$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
    }
}

: , ( ) (.*) .
, chap\d, :

echo 'count 1: ', isset($count[1]) ? count($count[1]) : 0, PHP_EOL;
+3

reg ex,

if (preg_match("/chap[0-9]{1,3}/i", $v, $match)) {
    $count++;
}
+1

:

$rest = substr($k, 0, 5);

($ rest! == 'chap1')

, .

0

PHP Online

<?php
    $_POST['chap1e1'] = 'test1';
    $_POST['chap10e1'] = 'test2';
    foreach($_POST as $k => $v){
    // for all types of questions of chapter 1 only
    $count = 0;
    var_dump($k);
    var_dump(strpos($k, 'chap1'));
    var_dump(strpos($k, 'chap1') !== false);
}
foreach($_POST as $k => $v){
    // for all types of questions of chapter 1 only
    //$count = 0;
    var_dump($count);
    if(strpos($k, 'chap1') !== false){
        $count++;
    }
}
echo $count;
?>

And get the bottom output string (7) "chap1e1" int (0) bool (true) string (8) "chap10e1" int (0) bool (true) int (0) int (1) 2

Indicating that strpos can find "chap1" in "chap10e1", but the total number of counters is wrong, because your code always reset $ count to 0 inside the foreach loop

0
source

All Articles