我有一个 Glype 代理,但我不想解析外部 URL。页面上的所有 URL 都会自动转换为:http://proxy.com/browse.php?u=[URL HERE]。示例:如果我在代理上访问海盗湾,那么我不想解析以下 URL:
ByteLove.com (Not to: http://proxy.com/browse.php?u=http://bytelove.com&b=0)
BayFiles.com (Not to: http://proxy.com/browse.php?u=http://bayfiles.com&b=0)
BayIMG.com (Not to: http://proxy.com/browse.php?u=http://bayimg.com&b=0)
PasteBay.com (Not to: http://proxy.com/browse.php?u=http://pastebay.com&b=0)
Ipredator.com (Not to: http://proxy.com/browse.php?u=https://ipredator.se&b=0)
etc.
我当然想保留内部 URL,所以:
thepiratebay.se/browse (To: http://proxy.com/browse.php?u=http://thepiratebay.se/browse&b=0)
thepiratebay.se/top (To: http://proxy.com/browse.php?u=http://thepiratebay.se/top&b=0)
thepiratebay.se/recent (To: http://proxy.com/browse.php?u=http://thepiratebay.se/recent&b=0)
etc.
是否有 preg_replace 可以替换除 thepiratebay.se 和子域之外的所有 URL(如示例中所示)?还欢迎其他功能。 (例如 domdocument、querypath、substr 或 strpos。不是 str_replace,因为这样我应该定义所有 URL)
我发现了一些东西,但我对 preg_replace 不熟悉:
$exclude = '.thepiratebay.se';
$pattern = '(https?\:\/\/.*?\..*?)(?=\s|$)';
$message= preg_replace("~(($exclude)?($pattern))~i", '$2<a href="$4" target="_blank">$5</a>$6', $message);
最佳答案
我猜您需要提供一个白名单来告诉哪些域应该被代理:
$whitelist = array();
$whitelist[] = "internal1.se";
$whitelist[] = "internal2.no";
$whitelist[] = "internal3.com";
// and so on...
$string = '<a href="http://proxy.org/browse.php?u=http%3A%2F%2Fexternal1.com&b=0">External link 1</a><br>';
$string .= '<a href="http://proxy.org/browse.php?u=http%3A%2F%2Finternal1.se&b=0">Internal link 1</a><br>';
$string .= '<a href="http://proxy.org/browse.php?u=http%3A%2F%2Finternal3.com&b=0">Internal link 2</a><br>';
$string .= '<a href="http://proxy.org/browse.php?u=http%3A%2F%2Fexternal2.no&b=0">External link 2</a><br>';
//Assuming the URL always is inside '' or "" you can use this pattern:
$pattern = '#(https?://proxy\.org/browse\.php\?u=(https?[^&|\"|\']*)(&?[^&|\"|\']*))#i';
$string = preg_replace_callback($pattern, "my_callback", $string);
//I had only PHP 5.2 on my server, so I decided to use a callback function.
function my_callback($match) {
global $whitelist;
// set return bypass proxy URL
$returnstring = urldecode($match[2]);
foreach ($whitelist as $white) {
// check if URL matches whitelist
if (stripos($match[2], $white) > 0) {
$returnstring = $match[0];
break; } }
return $returnstring;
}
echo "NEW STRING[:\n" . $string . "\n]\n";
关于php - Preg-replace - 替换除域及其子域之外的所有 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545946/