开发者

regex for extracting anchor in a url

I'm trying to extract an anchor tag and everything behind it fro开发者_JAVA百科m a url using preg_replace. I found one to remove everything after the #, but I want one that removes the # and everything behind it.

http://blah.com#removethis

Thanks, Steve


You can try the parse_url function:

$url = "http://blah.com#removethis";
print_r(parse_url($url));

fragment - after the hashmark #

Output:

Array
(
    [scheme] => http
    [host] => blah.com
    [fragment] => removethis
)


Another way without regex:

$newurl = substr($url, 0, strpos($url,"#")); 


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


$url = preg_replace('@#.*$@', '', $url);


Don't use regexes when there are proper library functions to do the job.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜