【问题标题】:Remove parts of a string with PHP使用 PHP 删除部分字符串
【发布时间】:2012-02-23 23:20:38
【问题描述】:

我有一个输入框,告诉用户输入来自 imgur.com 的链接 我想要一个脚本来检查指定站点的链接,但我不知道该怎么做?

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

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

【问题讨论】:

    标签: php string split


    【解决方案1】:

    试试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
    }
    

    【讨论】:

    • parse_url() 可能会失败,因此您需要在检查$input['host']之前确保它!== false
    • @simshaun 这是真的,但不是在“快速”答案中。我已经为你增强了答案
    • ???快速回答与否,这是必要的,否则您在代码中引入了潜在的错误。
    • 有没有办法让这个插入 http:// 取决于它是否被提供?
    【解决方案2】:
    substr($input, 0, strlen('http://i.imgur.com/')) === 'http://i.imgur.com/'
    

    【讨论】:

      【解决方案3】:

      检查这个,使用stripos

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

      【讨论】:

        【解决方案4】:

        试试这个:

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

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

        我没有测试过这段代码。

        【讨论】:

          【解决方案5】:
          $url_input = $_POST['input_box_name'];
          if ( strpos($url_input, 'http://i.imgur.com/') !== 0 )
          

          ...

          【讨论】:

          • 需要!== FALSE== 0。我会选择后者,因为您希望它作为字符串的开头。
          • !== FALSE 不会给我们位置检查,只是存在一个。 ) 而 ==0 是不正确的,因为它对 FALSE 的响应也相同。
          • 我暗示了位置检查,后者会更好。但是是的,你是对的,它必须是=== 0。编辑:刚刚意识到你可能意味着抛出错误的条件。无视我。
          【解决方案6】:

          有几种方法。这是一种:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-05-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-03-07
            • 2013-11-07
            • 2019-08-10
            • 1970-01-01
            相关资源
            最近更新 更多