【问题标题】:stristr, if string contains nothing (empty string)stristr,如果字符串不包含任何内容(空字符串)
【发布时间】:2011-10-25 14:58:50
【问题描述】:

我正在为我的网站进行搜索,当特定参数为 ''(无)时,我想显示所有结果。我尝试了以下方法,但没有成功。

<?php
$a = file("test.txt");
sort($a);
foreach ($a as $b) {
$c = explode("|", $b);
if (isset($_GET['name'])) {
    if (stristr($c[0], $_GET['name'])) {
        echo '<option value="' . $c[0] . '">' . $c[0] . '</option>';
    }
}
?>

而且这只是一个测试脚本,我将在上面的 if 语句中使用多个 GET。

【问题讨论】:

  • 你真的应该使用更合适的变量名而不是$a $b$c。例如使用$file$line$separated_line
  • 你什么时候想做什么?如果已设置且为空?

标签: php string foreach contains isset


【解决方案1】:
<?php
$a = file("test.txt");
sort($a);
foreach ($a as $b) {
$c = explode("|", $b);
    if ((isset($_GET['name']) && stristr($c[0], $_GET['name'])) || !isset($_GET['name']))
        echo '<option value="' . $c[0] . '">' . $c[0] . '</option>';

【讨论】:

    【解决方案2】:

    检查 stristr 是否返回 false..

    if (stristr($c[0], $_GET['name']) != FALSE)
    

    【讨论】:

      【解决方案3】:
      if (empty($_GET['name'])){
          echo '<option value="'.$c[0].'">'.$c[0].'</option>';
      }
      

      【讨论】:

        【解决方案4】:

        使用 empty 代替 isset。

        【讨论】:

          猜你喜欢
          • 2021-05-30
          • 1970-01-01
          • 2012-06-13
          • 2018-11-20
          • 1970-01-01
          • 2020-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多