【问题标题】:PHP - remove last part from URLPHP - 从 URL 中删除最后一部分
【发布时间】:2015-01-22 13:45:42
【问题描述】:

祝大家今天好!

我需要获取文章的 URL 并通过删除它的最后一部分来修改它(上移一级)。

使用 Wordpress 函数<?php echo get_permalink( $post->ID ); ?>获取当前 URL

使用示例。我当前文章的网址:

http://example.com/apples/dogs/coffee

删除 URL 的最后一部分,这样它将是:

http://example.com/apples/dogs

(最后没有斜线)

所以这将返回当前的 Wordpress URL:

<a href="<?php echo get_permalink( $post->ID ); ?>">Text</a>

但是我怎样才能删除它的最后一部分呢?

提前致谢!

【问题讨论】:

标签: php wordpress


【解决方案1】:
$url = 'http://example.com/apples/dogs/coffee';
$newurl = dirname($url);

【讨论】:

  • 谢谢!对于我的情况,这似乎是最简单,最准确的解决方案。我根据 Wordpress 对其进行了一些修改,所以它现在对我来说是一个理想的解决方案:&lt;?php echo dirname(get_permalink( $post-&gt;ID )); ?&gt;
【解决方案2】:

这里写的大部分答案都可以,但是使用explode 和RegExp 解析url 是一种不好的做法。最好使用PHP函数parse_url。在这种情况下,如果 url 发生变化,您不会遇到问题。此代码将省略 url 片段的最后一部分。

代码如下:

<?php
$url = 'http://example.com/apples/dogs/coffee';
$parsed_url = parse_url($url);
$fragment = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] : '';
$new_fragment = '';
if(!empty($fragment)){
    $fragment_parts = explode('/', $fragment);
    // Remove the last item
    array_pop($fragment_parts);
    // Re-assemble the fragment
    $new_fragment = implode('/', $fragment_parts);
}
// Re-assemble the url
$new_url = $scheme . '://' . $host . $new_fragment;
echo $new_url;
?>

【讨论】:

    【解决方案3】:

    看起来您只是在寻找帖子的父级。在这种情况下,您需要使用 'get_post_ancestors($post->ID)'。

    来自wordpress codex...

    </head>
    <?php
    
    /* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
    $class = '';
    /* is it a page */
    if( is_page() ) { 
        global $post;
            /* Get an array of Ancestors and Parents if they exist */
        $parents = get_post_ancestors( $post->ID );
            /* Get the top Level page->ID count base 1, array base 0 so -1 */ 
        $id = ($parents) ? $parents[count($parents)-1]: $post->ID;
        /* Get the parent and set the $class with the page slug (post_name) */
            $parent = get_page( $id );
        $class = $parent->post_name;
    }
    ?>
    
    <body <?php body_class( $class ); ?>
    

    【讨论】:

      【解决方案4】:

      这将满足您的要求 -

       echo implode('/',array_slice(explode('/',get_permalink( $post->ID )),0,-1))
      

      但它很弱。

      如果您能保证在您需要保留的 URL 的末尾不会有任何其他内容,请仅使用如此简单的解决方案。

      【讨论】:

      • 谢谢,这个解决方案也有效!但是&lt;?php echo dirname(get_permalink( $post-&gt;ID )); ?&gt; 对我来说似乎更有效。
      【解决方案5】:

      有很多方法(explode、strpos 和 substr、regex)。使用正则表达式,您可以执行以下操作:

      $url = 'http://example.com/apples/dogs/coffee';
      $url = preg_replace('#/[^/]+?$#', '', $url);
      

      【讨论】:

        猜你喜欢
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多