PHP 正则表达式preg_match包含 URL 的变量上


php regex preg_match on a variable containing a url

我正在尝试在 url 上运行正则表达式以提取主机之后的所有段。当主机段位于变量中时,我无法让它工作,我不确定如何让它工作

// this works
if(preg_match("/^http':'/'/myhost('/[a-z0-9A-Z-_'/.]*)$/", $url, $matches)) {
  return $matches[2];
}
// this doesn't work
$siteUrl = "http://myhost";
if(preg_match("/^$siteUrl('/[a-z0-9A-Z-_'/.]*)$/", $url, $matches)) {
  return $matches[2];
}
// this doesn't work
$siteUrl = preg_quote("http://myhost");
if(preg_match("/^$siteUrl('/[a-z0-9A-Z-_'/.]*)$/", $url, $matches)) {
  return $matches[2];
}

在PHP中,有一个名为parse_url的函数。(类似于您尝试通过代码实现的内容)。

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>

输出:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

您忘记在变量声明中转义/。一种快速解决方法是将正则表达式分隔符从 / 更改为 #尝试

$siteUrl = "http://myhost";
if(preg_match("#^$siteUrl('/[a-z0-9A-Z-_'/.]*)$#", $url, $matches)) { //note the hashtags!
  return $matches[2];
}

或者不更改正则表达式分隔符:

$siteUrl = "http:'/'/myhost"; //note how we escaped the slashes
if(preg_match("/^$siteUrl('/[a-z0-9A-Z-_'/.]*)$/", $url, $matches)) { //note the hashtags!
  return $matches[2];
}