PHP 正则表达式:如何删除 url 中的文件


PHP regex: How to remove ?file in url?

我的网址是这样的:

http://mywebsite.com/movies/937-lan-kwai-fong-2?file=Rae-Ingram&q=
http://mywebsite.com/movies/937-big-daddy?file=something&q=

我想得到"lan-kwai-fong-2"和"big-daddy",所以我使用了这段代码,但它不起作用。请帮我修复它!如果你能缩短它,那就太好了!

    $url= $_SERVER['REQUEST_URI'];
preg_replace('/'?file.*/','',$url);
preg_match('/[a-z]['w'-]+$/',$url,$matches);
$matches= str_replace("-"," ",$matches[0]);

首先,您的代码存在问题,我将要讨论这些问题,因为它们是一般的东西:

  1. preg_replace 通过引用不起作用,因此您永远不会实际修改 URL。您需要将替换结果分配给变量:

    // this would ovewrite the current value of url with the replaced value
    $url = preg_replace('/'?file.*/','',$url);
    
  2. preg_match可能找不到任何东西,所以你需要测试结果

    // it should also be noted that sometimes you may need a more exact test here
    // because it can return false (if theres an error) or 0 (if there is no match) 
    if (preg_match('/[a-z]['w'-]+$/',$url,$matches)) {
      // do stuff
    }
    

现在有了这个,你正在使这比它需要的更加困难。有特定的功能来处理网址parse_urlparse_str

您可以使用这些来轻松处理信息:

$urlInfo = parse_url($_SERVER['REQUEST_URI']);
$movie = basename($urlInfo['path']); // yields 937-the-movie-title

只需替换

preg_replace('/'?file.*/','',$url);

$url= preg_replace('/'?file.*/','',$url);

正则表达式有效,parse_url是正确的方法。 但是对于快速而肮脏的东西,我通常会使用爆炸。 我认为它更清楚。

@list($path, $query) = explode("?", $url, 2); // separate path from query
$match = array_pop(explode("/", $path));      // get last part of path

这个怎么样:

$url = $_SERVER['REQUEST_URI'];
preg_match('/'/[^-]+-([^?]+)'?/', $url, $matches);
$str = isset($matches[1]) ? $matches[1] : false;`
  1. 匹配最后一个 '/'
  2. 匹配除"-"以外的任何内容,直到"-"
  3. 捕获除"?"之外的任何内容,直到(不包括)"?"