用PHP删除字符串的一部分

时间:2012-02-23 23:20:38

标签: php string split

我有一个输入框,告诉他们输入imgur.com的链接 我想要一个脚本来检查链接是否适用于指定的网站,但我不会起诉如何做到这一点?

链接如下:http://i.imgur.com/He9hD.jpg 请注意,在/之后,文字可能会有所不同,例如:不是jpg,但主域名始终是http://i.imgur.com/

任何帮助表示赞赏。 谢谢,Josh。(新手)

6 个答案:

答案 0 :(得分:3)

尝试parse_url()

try {
    if (!preg_match('/^(https?|ftp)://', $_POST['url']) AND !substr_count($_POST['url'], '://')) {
        // Handle URLs that do not have a scheme
        $url = sprintf("%s://%s", 'http', $_POST['url']);
    } else {
        $url = $_POST['url'];
    }

    $input = parse_url($url);

    if (!$input OR !isset($input['host'])) {
        // Either the parsing has failed, or the URL was not absolute
        throw new Exception("Invalid URL");
    } elseif ($input['host'] != 'i.imgur.com') {
        // The host does not match
        throw new Exception("Invalid domain");
    }

    // Prepend URL with scheme, e.g. http://domain.tld
    $host = sprintf("%s://%s", $input['scheme'], $input['host']);
} catch (Exception $e) {
    // Handle error
}

答案 1 :(得分:2)

substr($input, 0, strlen('http://i.imgur.com/')) === 'http://i.imgur.com/'

答案 2 :(得分:2)

使用stripos

进行检查
if(stripos(trim($url), "http://i.imgur.com")===0){
 // the link is from imgur.com
}

答案 3 :(得分:1)

$url_input = $_POST['input_box_name'];
if ( strpos($url_input, 'http://i.imgur.com/') !== 0 )

...

答案 4 :(得分:1)

这样做的几种方式..这是一个:

if ('http://i.imgur.com/' == substr($link, 0, 19)) {
    ...
}

答案 5 :(得分:1)

试试这个:

<?php
if(preg_match('#^http\:\/\/i\.imgur.com\/#', $_POST['url']))
    echo 'Valid img!';
else
    echo 'Img not valid...';
?>

其中$ _POST ['url']是用户输入。

我还没有测试过这段代码。

相关问题