代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何检查字符串是否以指定的字符串开头?[副本]

php
  •  386
  • Andrew  · 技术社区  · 15 年前

    这个问题已经有了答案:

    我想检查一根绳子是否以 http . 这张支票怎么办?

    $string1 = 'google.com';
    $string2 = 'http://www.google.com';
    
    6 回复  |  直到 6 年前
        1
  •  672
  •   NoDataDumpNoContribution    10 年前
    substr( $string_n, 0, 4 ) === "http"
    

    如果你想确定这不是另一个协议。我会用 http:// 相反,因为https也会匹配,以及其他东西,比如http-protocol.com。

    substr( $string_n, 0, 7 ) === "http://"
    

    一般来说:

    substr($string, 0, strlen($query)) === $query
    
        2
  •  518
  •   Kyle    7 年前

    使用 strpos() :

    if (strpos($string2, 'http') === 0) {
       // It starts with 'http'
    }
    

    记住这三个等号( === )如果你只用两个,它就不能正常工作。这是因为 strpos()。 会回来的 false 如果大海捞针找不到的话。

        3
  •  69
  •   dave    7 年前

    还有 strncmp() 功能和 strncasecmp() 适合这种情况的功能:

    if (strncmp($string_n, "http", 4) === 0)
    

    一般来说:

    if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
    

    相对于 substr() 方法是 strncmp()。 只需执行需要执行的操作,而不创建临时字符串。

        4
  •  38
  •   user276648 Jeremy Cook    11 年前

    您可以使用一个简单的regex(用户更新的版本 病毒属 作为 eregi 已弃用)

    if (preg_match('#^http#', $url) === 1) {
        // Starts with http (case sensitive).
    }
    

    或者如果你想要不区分大小写的搜索

    if (preg_match('#^http#i', $url) === 1) {
        // Starts with http (case insensitive).
    }
    

    正则表达式允许执行更复杂的任务

    if (preg_match('#^https?://#i', $url) === 1) {
        // Starts with http:// or https:// (case insensitive).
    }
    

    从性能上讲,如果字符串不是以您想要的开头,您不需要创建新的字符串(与SUBSTR不同),也不需要解析整个字符串。尽管第一次使用regex(您需要创建/编译它)时会有性能损失。

    此扩展维护已编译规则的全局每线程缓存 表达式(最多4096个)。 http://www.php.net/manual/en/intro.pcre.php

        5
  •  5
  •   Salim    6 年前

    您可以使用下面的小函数检查字符串是否以HTTP或HTTPS开头。

    function has_prefix($string, $prefix) {
       return substr($string, 0, strlen($prefix)) == $prefix;
    }
    
    $url   = 'http://www.google.com';
    echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
    echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';
    
        6
  •  -6
  •   viriathus    15 年前

    同时工作:

    if (eregi("^http:", $url)) {
     echo "OK";
    }
    
    推荐文章