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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog