PHP 正则表达式 我如何确定/检查preg_match找到单个值或多个值


PHP Regex How i can determined / check preg_match find single value or multiple values

in PHP Regex 我如何确定或检查preg_match找到单个值或多个值。

我的意思是,如果preg_match找到多个值,那么如果找到单个值,则执行此操作

<td class"page"> 
<span class="my-tag">value1</span>
<span class="my-tag">value2</span>
<span class="my-tag">value3</span>
<span class="my-tag">value4</span>
</td>

现在当我使用像 as 这样的preg_match

preg_match('/<td class"page">(.*?)<'/td>/s', $page, $string);

如果$string包含4 values则意味着它找到多个值,然后执行回显"mutliple values";

<td class"page"> 
<span class="my-tag">value3</span>
</td>

现在我用

preg_match('/<td class"page">(.*?)<'/td>/s', $page, $string);

如果它$string1 value则意味着它找到单个值,然后执行echo "single value";

您的帮助将不胜感激!

preg_match

$string变量作为数组返回,因此您可以检查数组的大小并从那里进行确定。

例如
if(count($string) == 1) {
 // found one result
} else if (count($string) > 1) {
 // found multiple results 
} else {
 // not found results
}

有关preg_match的更多信息!

>preg_match()将返回$string匹配项数组,您可以使用count()来确定该数组中的值数。解决方案如下所示:

if('/<td class"page">(.*?)<'/td>/s', $page, $string){
    //a match was found
    if(count($string) > 1){
        //multiple matches were found
    }
    else{
        //only one match was found
    }
}
else{
    //no matches were found
}

附言 sizeof()count() 的别名