首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用php regex从宏中修剪到根域的链接(查看内幕)

使用php regex从宏中修剪到根域的链接(查看内幕)
EN

Stack Overflow用户
提问于 2012-03-30 03:12:02
回答 2查看 467关注 0票数 0

我的php脚本包含宏===shortlink===。此宏位于EOF容器中

代码语言:javascript
复制
<?php
$gtemplate=<<<EOF
 ===shortlink===
EOF;
?>

===shortlink===包含这样的http://site.com/2012/blog-post.html,当我运行脚本时,它显示了来自===shortlink===的结果。像http://site.com/2012/blog-post.html这样的网址。我需要修剪url从这个宏来只显示域名为site.com。建议我如何修剪它在这个宏用php正则表达式?

看起来这个宏应该返回到特殊的var,然后修剪,然后返回到====shortlink===。嘿,大师们,你们能打败它吗?

我试过这样的东西

代码语言:javascript
复制
$urlpage = '===shortlink===';
preg_match_all("/((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])/", $urlpage, $replurl, PREG_PATTERN_ORDER);

    $replurl= '===shortlink===';

但它不起作用。请帮我做一下这个简单的替换。

EN

回答 2

Stack Overflow用户

发布于 2012-03-30 03:15:56

为什么不使用parse_url()

代码语言:javascript
复制
<?php
    $url = "http://site.com/2012/blog-post.html";

    $parsed = parse_url($url);
    echo $parsed["host"];
票数 1
EN

Stack Overflow用户

发布于 2013-11-09 23:53:53

在这里你可以通过: ctrtard.com查看完整的工作代码,特别感谢。

代码语言:javascript
复制
<?php
function trim_url_to_root_domain($target) {
/* Usage:
* echo trim_url_to_root_domain("http://mytarget.com");
* or
* echo ucfirst(trim_url_to_root_domain("http://mytarget.com")); // uppercase first letter
*/
    // trim http, https, and //
    $target = str_replace("http:", "", $target);
    $target = str_replace("https:", "", $target);
    $target = str_replace("//", "", $target);

    // check for dots
    $dots = substr_count($target, '.');
    if ($dots > 1) { // if there are more than 1 dots, we need to remove subdomain
        $first_dot = strpos ($target, ".");
        $target = substr($target, $first_dot+1, strlen($target));
    }

    // find the last slash, this should be the slash just before directory info
    $last_slash = strripos($target, "/");
    if ($last_slash > 0 ) {
        $target = substr($target, 0, $last_slash);
    }

    // find last slash one more time, to handle targets like /domain.com
    $last_slash = strripos($target, "/");
    if ($last_slash !== FALSE ) {
        $target = substr($target, 1, strlen($target));
    }

    // normalize target so it's all lower case
    $target = strtolower($target);

    return $target;
}


echo trim_url_to_root_domain("http://mytarget.com");

echo ucfirst(trim_url_to_root_domain("http://mytarget.com"));
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9931894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档