【问题标题】:PHP, Delete parts of a URL variable [duplicate]PHP,删除部分 URL 变量 [重复]
【发布时间】:2013-06-23 00:05:06
【问题描述】:

我有以下 php 变量

$currentUrl

这个 php 变量返回给我当前的 url 页面。例如:它返回:

http://example.com/test-category/page.html?_ore=norn&___frore=norian

我可以使用什么 php 代码来获取这个 url 链接并删除 ".html" 之后的所有内容,并返回一个干净的 url 链接,例如:

http://example.com/test-category/page.html

这将在一个新变量 $clean_currentUrl

中返回

【问题讨论】:

标签: php


【解决方案1】:

用 PHP 的 parse_url()

<?php 
$url = "http://example.com/test-category/page.html?_ore=norn&___frore=norian";
$url = parse_url($url);

print_r($url);
/*
Array
(
    [scheme] => http
    [host] => example.com
    [path] => /test-category/page.html
    [query] => _ore=norn&___frore=norian
)
*/
?>

然后您可以根据这些值构建您想要的 url。

$clean_url = $url['scheme'].'://'.$url['host'].$url['path'];

【讨论】:

  • 您的建议也很有效。谢谢你的回答
  • 这应该是公认的答案。这是完成这项工作的正确工具。
  • 嗨,TecBrat,这是真的,这也是正确的答案,我希望我能接受它们都是正确的。我将 parse_url() 和 preg_match 用于不同的目的。重要的想法是我了解了这两种解决方案
  • 我正在使用“parse_url($currentUrl2, PHP_URL_PATH);”它返回给我“example.com/test-category/page.html”我如何让它也把“http://”返回给我“http://example.com/test-category/page. html"
  • 只是从上面回答我自己的问题,这就是解决方案:"$clean_url = parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST).parse_url( $url, PHP_URL_PATH);"
【解决方案2】:

类似这样的:

<?php
$currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian';

preg_match('~http:\/\/.*\.html~', $currentUrl, $matches);
print_r($matches);

请参阅下面的 amigura 评论。要处理这种情况,请更改正则表达式:

<?php
$currentUrl = 'http://example.com/test-category/page.html?_ore=norn&___frore=norian';

preg_match('~(http:\/\/.*\..+)\?~', $currentUrl, $matches);
print_r($matches);

【讨论】:

  • 感谢 Ruben 提供的代码,它确实返回了一个干净的 url,但它还添加了一些其他内容。这是它使用您的代码返回的内容:“Array ([0] => example.com/test-category/page.html)”
  • 我怎样才能让它返回一个干净的“example.com/test-category/page.html?”乞求中没有“数组([0] =>”,最后没有“)”
  • print_r 只是为了向您展示结果。您实际上可以使用 $matches[0] 来获取结果: echo $matches[0];
  • Array(... 是 print_r 函数的输出,它是如何显示数据的。
  • 谢谢,现在完美了:)
【解决方案3】:
$parts = explode('?', $currentUrl);
$url = $parts[0];

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2015-07-04
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多