如何在PHP中提取URL的一部分以删除特定部分?

ach*_*art 4 php regex url

所以,我在一个字符串中有这个URL:

http://www.domain.com/something/interesting_part/?somevars&othervars
Run Code Online (Sandbox Code Playgroud)

在PHP中,我怎么能摆脱所有interesting_part呢?

Sar*_*raz 5

...

$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];
Run Code Online (Sandbox Code Playgroud)

输出:

interesting_part
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚发帖时写的是这样的:D (2认同)

Kam*_*zot 5

尝试:

<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';

preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么有人对此做了"-1".它相当于爆炸的东西.我把它推回到0 :) (2认同)

Ond*_*ták 5

您应该使用parse_url对 URL 进行操作。首先解析它,然后进行您想要的更改,例如使用爆炸,然后将其重新组合在一起。

$uri = "http://www.domain.com/something/interesting_part/?somevars&othervars";
$uri_parts = parse_url( $uri );

/*
you should get:
 array(4) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(14) "www.domain.com"
  ["path"]=>
  string(28) "/something/interesting_part/"
  ["query"]=>
  string(18) "somevars&othervars"
}
*/

...

// whatever regex or explode (regex seems to be a better idea now)
// used on $uri_parts[ "path" ]

...

$new_uri = $uri_parts[ "scheme" ] + $uri_parts[ "host" ] ... + $new_path ... 
Run Code Online (Sandbox Code Playgroud)