dopzc64662 2016-11-10 16:50
浏览 36
已采纳

修剪斜线和时期的网址

I am trying to validate a URL when i am sending it through a form, I want to make sure it begins with either https or http, has at least one period, and then doesn't have a period or trailing slash at the end. I have achieved the http and period bit through the use of regex, however I can't seem to work out how to trim the url if it has either . , ./ , /. or / I use rtrim but it only works if it finds the single characters, is there a way to remove both of them if appear?

Here is my code:

//update the canonical url
        $canonical_url = $_POST ['canonical_url'];
        $valid_url =  preg_match('/^(http[s]?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', $canonical_url );
        if ($valid_url) {
            $removed_period = rtrim($canonical_url, '.');
            $final_canonical = rtrim($removed_period, '/');
        }
  • 写回答

1条回答 默认 最新

  • douliang1900 2016-11-10 18:42
    关注

    You could use filter_var to validate your URL and preg_replace to trim the trailing ., ./, /. or /, if any.

    $canonical_url = $_POST['canonical_url'];
    if (filter_var($canonical_url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
        $final_canonical = preg_replace('/(\.|\.\/|\/\.|\/)$/', '', $canonical_url);
    }
    

    Note that FILTER_VALIDATE_URL allows any RFC 2396 compliant URI, so if you only admit http/https, you could add:

    if(filter_var(…) && strpos($canonical_url, 'http') !== false) {…}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭