PHP - 从URL中删除最后一部分

3

大家好!

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

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

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

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

删除URL的最后一部分,使其变为:
http://example.com/apples/dogs

这将返回当前WordPress网址:

(并且结尾没有斜杠)

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

但是我该如何删除它的最后一部分呢?提前感谢!

3
看一下explode,那应该能帮助你入门。 - Styphon
URL的格式取决于WP网站的设置。如果它没有使用重写URL,这会出现问题,不是吗? - Reactgular
可能是重复问题 - https://dev59.com/CnE95IYBdhLWcg3wKqsk - Amit Verma
可能是从URL中删除最后一个元素的重复问题。 - jeffl8n
你们提到的链接都没有指向正确的解决方案。这是一个wordpress问题,因此不是php问题的重复。 - Gavin Simpson
对于任何感兴趣的人,我选择了 <?php echo dirname(get_permalink( $post->ID )); ?> 作为这个任务的解决方案。 - Albert
5个回答

10
$url = 'http://example.com/apples/dogs/coffee';
$newurl = dirname($url);

1
谢谢!这个似乎是我情况下最简单和最准确的解决方案。我根据WordPress进行了一些修改,所以现在它对我来说是一个理想的解决方案:<?php echo dirname(get_permalink( $post->ID )); ?> - Albert

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;
?>

2

看起来您只是想找到一篇文章的父级。这种情况下,您需要使用“get_post_ancestors($post->ID)”。

根据WordPress 文档...

</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 ); ?>

1
这将做你所要求的 -
 echo implode('/',array_slice(explode('/',get_permalink( $post->ID )),0,-1))

但它很脆弱。
只有在您可以保证URL末尾没有任何需要保留的附加内容时,才使用这样简单的解决方案。

1
谢谢,这个解决方案也可行!但是对我来说,<?php echo dirname(get_permalink( $post->ID )); ?> 看起来更有效一些。 - Albert

1

有很多方法(explode、strpos和substr、正则表达式)可以用于编程。使用正则表达式,您可以像这样处理:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接