Check if variable starts with 'http'

前端 未结 6 1559
萌比男神i
萌比男神i 2020-12-03 20:56

I\'m sure this is a simple solution, just haven\'t found exactly what I needed.

Using php, i have a variable $source. I wanna check if $source starts with \'http\'.

相关标签:
6条回答
  • 2020-12-03 21:17

    As of PHP 8.0 there is method str_starts_with implemented:

    if (str_starts_with($source, 'http')) {
        $source = "<a href='$source'>$source</a>";
    } 
    
    0 讨论(0)
  • 2020-12-03 21:22
    if(strpos($source, 'http') === 0)
        //Do stuff
    
    0 讨论(0)
  • 2020-12-03 21:28

    You want the substr() function.

    if(substr($source, 0, 4) == "http") {
       $source = "<a href='$source'>$source</a>";
    }
    
    0 讨论(0)
  • 2020-12-03 21:34
    if (strpos($source, 'http') === 0) {
        $source = "<a href=\"$source\">$source</a>";
    }
    

    Note I use ===, not == because strpos returns boolean false if the string does not contain the match. Zero is falsey in PHP, so a strict equality check is necessary to remove ambiguity.

    Reference:

    http://php.net/strpos

    http://php.net/operators.comparison

    0 讨论(0)
  • 2020-12-03 21:39

    Use substr:

    if (substr($source, 0, 4) === 'http')
    
    0 讨论(0)
  • 2020-12-03 21:41
    if(preg_match('/^(http)/', $source)){
    ...
    }
    
    0 讨论(0)
提交回复
热议问题