开发者

regex for extracting anchor in a url

开发者 https://www.devze.com 2023-01-04 08:46 出处:网络
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 everythi

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

精彩评论

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

关注公众号