0

I'm trying to run a regex on a url to extract all the segments after the host. I can't get it working when the host segment is in a variable and i'm not sure how to get it working

// 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];
}
asked Nov 16, 2013 at 6:21

2 Answers 2

4

In PHP, there is a function called parse_url. (Something similar to what you are trying to achieve through your code).

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

OUTPUT :

Array
(
 [scheme] => http
 [host] => hostname
 [user] => username
 [pass] => password
 [path] => /path
 [query] => arg=value
 [fragment] => anchor
)
/path
answered Nov 16, 2013 at 6:24
Sign up to request clarification or add additional context in comments.

Comments

2

You forgot to escape the / in your variable declaration. One quick fix is to change your regex delimiter from / to #. Try:

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

Or without changing the regex delimiter:

$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];
}
answered Nov 16, 2013 at 6:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.