在数组字符串元素中搜索char时的奇怪行为

时间:2013-09-11 06:53:57

标签: php string strpos strcmp strstr

<?php

ini_set('error_reporting', '-1');
ini_set('display_errors', '1');
ini_set('apc.enabled', '0');
gc_enable();

$array = array("php", "php_php", "php_php", "php_php", "php");
$arraysize = count($array);
$style = " style='border: 1px solid black;'";
$strcmpcharcount = 0;
$equalcmpcharcount = 0;

foreach ($array as $key)
{
  $strcmpcharcount = 0;
  $equalcmpcharcount = 0;

  if (strstr($key, "_") !== false)
  {
    $strstr[] = "found";
    $explodedstring1[] = explode("_", $key);
  }
  else
  {
    $strstr[] = "not found";
    $explodedstring1[] = "not found";
  }

  if (strpos($key, "_") !== false)
  {
    $strpos[] = "found";
    $explodedstring2[] = explode("_", $key);
  }
  else
  {
    $strpos[] = "not found";
    $explodedstring2[] = "not found";
  }

  if (preg_match("/[^_+$]/", $key))
  {
    $preg_match[] = "found";
    $explodedstring3[] = explode("_", $key);
  }
  else
  {
    $preg_match[] = "not found";
    $explodedstring3[] = "not found";
  }

  $keysize = strlen($key);
  for ($i = 0; $i < $keysize; $i++)
  {
    if (strcmp($key[$i], "_") === 0) { $strcmpcharcount++; }
  }

  for ($j = 0; $j < $keysize; $j++)
  {
    if ($key[$j] === "_") { $equalcmpcharcount++; }
  }

  if ($strcmpcharcount > 0)
  {
    $strcmp[] = "found";
    $explodedstring4[] = explode("_", $key);
  }
  else
  {
    $strcmp[] = "not found";
    $explodedstring4[] = "not found";
  }

  if ($equalcmpcharcount > 0)
  {
    $equalcmp[] = "found";
    $explodedstring5[] = explode("_", $key);
  }
  else
  {
    $equalcmp[] = "not found";
    $explodedstring5[] = "not found";
  }
}
echo "<table$style>
<th$style>
<tr>
<td$style>strstr()</td>
<td$style>strpos()</td>
<td$style>preg_match()</td>
<td$style>strcmp()</td>
<td$style>'==='</td>
</tr>
</th>";
for($k = 0; $k < $arraysize; $k++)
{
  echo "<tr>
  <td$style>$strstr[$k]</td>
  <td$style>$strpos[$k]</td>
  <td$style>$preg_match[$k]</td>
  <td$style>$strcmp[$k]</td>
  <td$style>$equalcmp[$k]</td>
  </tr>";
}
echo "</table>";

exit();

?>

问题在于前两个函数 - 它们随机找不到下划线字符。事实上,我打了50多次脚本来获得正确的结果。添加和preg_match()测试,但只知道我不确定它是否有有效的正则表达式。

1 个答案:

答案 0 :(得分:0)

您正在向$strstr$strpos表等添加新元素,最后您执行for...并从这些表中打印$k键不要必须存在。

检查这些表上的var_dumpprint_r,您会发现实际上他们有元素,但他们的索引与$array索引不匹配(我想这就是你想要实现)。

您可以将foreach ($array as $key)更改为foreach ($array as $index => $key),将$strstr[] = "found";更改为$strstr[$index] = "found";(也适用于其他识别方法),然后再次运行脚本以查看结果。< / p>

在最后一个块(for($k = 0; $k < $arraysize; $k++)...)中,您应该在打印之前验证$strstr[$k](和其他数组)是否存在,或者foreach分别打印这些数组。

您还可以为结果创建一个表,并将其作为多维,将函数名称作为第一级中的键,并将结果放在那里。