PHP 正则表达式用于在数组中查找问号


Php Regular expression to find question mark in an array

我想检查数组值是否包含'?'。如果是,则必须提取字符后面的问号。谢谢。

这是我的代码:

<?php
// Assume the Url to be localhost/demo/index.php?set=1
$path = explode('/',$_SERVER['REQUEST_URI']);
if (strpos($path[2], '?') !== false) {
echo "found";
}
?>

如何使用preg_match实现相同的效果?

数组还是字符串?在数组中,它不像字符被捆绑在一起。假设你的意思是一个字符串,你可以试试

<?php
$haystack="testata?basdasd";
$needle="?";
 $pos = strpos($haystack,$needle);
 if($pos!==FALSE && $haystack[$post+1]!="")
  echo $haystack[$pos+1];
?>

利用in_array()..比正则表达式快

<?php
$a = array('1','?','3');
$needle = '?';
if(in_array($needle,$a))
{
    echo $needle;
}

假设您的问题意味着数组中的字符串中是否有"?"字符:

没有正则表达式:

<?php
   for($i = 0; $i < count($array); $i++) {
     if (strpos($array[$i], '?') !== false) {
       // you found your item, use the $i index and break the loop
     }
   }
?>

使用正则表达式:

<?php
   for($i = 0; $i < count($array); $i++) {
     if (preg_match('/'?/', $array[$i])) {
       // you found your item, use the $i index and break the loop
     }
   }
?>
$storedText = [];
Foreach($arrray as $a){
   $postion = strpos($a,"?");
   If($position !== false){
      $succeedingText = substr($a,$position);
      $storedText[] = $succeedingText;
   }
}

比$storedText是一个数组,所有文本都后缀了 ?在包含 ?