【问题标题】:parse url with php to remove or alter sections用 php 解析 url 以删除或更改部分
【发布时间】:2013-11-20 17:13:38
【问题描述】:

假设您有两个网址。

http://testing.org/directory/index.php/arg1/arg2
Array ( [scheme] => http [host] => testing.org [path] => /directory/index.php/arg1/arg2 ) 

或者是这样的:

http://testing.org/index.php/arg1/arg2
Array ( [scheme] => http [host] => testing.org [path] => /index.php/arg1/arg2 ) 

我知道你可以用 parse_array() 分解 url。当我这样做时,路径就是“testing.org”之后的一切。在第一个示例中,数组中的路径变量 1 是“目录”,但在第二个示例中,路径变量 1 是“index.php”。

我想弄清楚做两件事的热度。首先删除 index.php 之后的所有内容,但我一直在摸索。另外,如何从第一个 url 中删除“/directory/”?

但我也想了解如何替换路径的一部分。

【问题讨论】:

  • 您能否展示您的代码并准确解释其与预期不符的地方?

标签: php parsing url url-parsing


【解决方案1】:

您可以结合使用parse_url() 和正则表达式来完成此操作。下面的正则表达式将删除 URL 路径中 index.php 之后的所有内容。

$parts = parse_url($url);
$scriptname = preg_replace('#(index\.php)/.*#', '$1', $parts['path']);
$result = $parts['scheme'].'://'. $parts['host'] . $scriptname;

对于给出问题的两个 URL,输出如下:

http://testing.org/directory/index.php
http://testing.org/index.php

Demo.

【讨论】:

  • 感谢您帮助非程序员!
  • @user2070436:那就开始学习吧!好有趣。无论如何,我很高兴能帮上忙。干杯!
猜你喜欢
  • 2013-09-21
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多