【问题标题】:Look for a word in a string PHP在字符串 PHP 中查找单词
【发布时间】:2012-08-07 07:01:35
【问题描述】:

如何检查字符串中的特定工作是否可用?假设我有一个这样的字符串

错误=姓名&密码&电子邮件

所以我想检查姓名、密码或/和电子邮件是否在字符串中。我需要布尔值的答案,以便我可以在那里做一些事情。

【问题讨论】:

标签: php string word boolean preg-match


【解决方案1】:
<?php
$mystring = 'wrong=name&pass&email';
$findme   = 'name';
$pos = strpos($mystring, $findme);


if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?> 

【讨论】:

    【解决方案2】:
    if ( stristr( $string, $string_im_looking_for) ){
         echo 'Yep!';
    }
    

    【讨论】:

      【解决方案3】:

      使用strstr()

      if (strstr($string,'pass'))
      {
          echo"pass is here";
      }
      

      【讨论】:

        【解决方案4】:

        你可以先把字符串炸开。像这样的东西;

        $arrayOfWords = explode('&', $yourString);
        

        然后循环遍历数组并检查 isset。

        【讨论】:

          【解决方案5】:

          从您的示例的外观看来,您实际上想要做的是解析查询字符串,例如parse_str:

          parse_str($string, $result);
          if(isset($result['name']))
            // Do something
          

          但是,如果字符串可能格式错误等。我建议使用strpos,与strstr 和其他人不同,它不需要创建新字符串。

          // Note the `!==` - strpos may return `0`, meaning the word is there at
          // the 0th position, however `0 == false` so the `if` statement would fail
          // otherwise.
          if(strpos($string, 'email') !== false)
            // Do something
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-12-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多