【问题标题】:Check if string contains a string in PHP检查字符串是否包含PHP中的字符串
【发布时间】:2012-06-23 17:31:46
【问题描述】:

我想知道如果该IP地址具有x字符串,我如何检查I字符串(特别是IP地址)

例如

$ip = "66.124.61.23" // ip of the current user
$x = "66.124" // this is the string what I want to check in my $ip.

那么如何检查 $ip 是否有 $x 字符串?

如果您很难理解这种情况,请发表评论。

谢谢。

【问题讨论】:

标签: php mysql string


【解决方案1】:

使用strstr()

if (strstr($ip, $x))
{
    //found it
}

另见:

  • stristr() 表示此函数不区分大小写。
  • strpos() 查找第一次出现的字符串
  • stripos()查找字符串中不区分大小写的子字符串第一次出现的位置

【讨论】:

  • strpos 在这里更合适。
【解决方案2】:

您也可以使用strpos(),如果您专门寻找字符串的开头(如您的示例中所示):

if (strpos($ip, $x) === 0)

或者,如果您只是想查看它是否在字符串中(而不关心它在字符串中的 where 位置:

if (strpos($ip, $x) !== false)

或者,如果要比较开头的 n 个字符,请使用 strncmp()

if (strncmp($ip, $x, strlen($x)) === 0) {
    // $ip's beginning characters match $x
}

【讨论】:

    【解决方案3】:

    使用strstr()

    $email  = 'name@example.com';
    $domain = strstr($email, '@');
    echo $domain; // prints @example.com
    

    根据$domain判断是否找到字符串(如果domain为null,则找不到字符串)

    此函数区分大小写。对于不区分大小写的搜索,请使用stristr()

    您也可以使用 strpos()

    $mystring = 'abc';
    $findme   = 'a';
    $pos = strpos($mystring, $findme);
    
    // Note our use of ===.  Simply == would not work as expected
    // because the position of 'a' was the 0th (first) character.
    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";
    }
    

    另请阅读之前的帖子,How can I check if a word is contained in another string using PHP?

    【讨论】:

      【解决方案4】:

      使用strpos()

      if(strpos($ip, $x) !== false){
          //dostuff
      }
      

      注意使用双等号以避免类型转换。 strpos 可以返回 0(在您的示例中将返回),这将使用单个等号评估为 false。

      【讨论】:

        猜你喜欢
        • 2011-11-09
        • 2013-05-18
        • 1970-01-01
        • 2014-03-03
        • 2011-01-21
        • 2015-04-11
        • 2021-12-20
        • 2014-09-17
        • 2012-05-16
        相关资源
        最近更新 更多