2013-11-16 2 views
0

Я пытаюсь запустить регулярное выражение на URL-адресе, чтобы извлечь все сегменты после хоста. Я не могу заставить его работать, когда сегмент хост находится в переменной, и я не знаю, как заставить его работатьphp regex preg_match для переменной, содержащей 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]; 
} 

ответ

2

Вы забыли, чтобы избежать / в вашей декларации переменной. Одним быстрым решением является изменение ограничителя регулярного выражения от / до #. Попробуйте:

$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]; 
} 
4

В PHP есть функция называется parse_url. (Что-то похожее на то, что вы пытаетесь достичь с помощью своего кода).

<?php 
$url = 'http://username:[email protected]/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 
+0

удивительного спасибо за это – user391986