tags:

views:

143

answers:

5

I'm trying to extract an anchor tag and everything behind it from 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

+2  A: 
$url = preg_replace('/#.*$/', '', $url);
Lauri Lehtinen
+1  A: 
$url = preg_replace('@#.*$@', '', $url);
ceejayoz
+1 for being just as fast :-)
Lauri Lehtinen
+10  A: 

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
)
Russell Dias
thx, you guys rock.
Steve
+3  A: 

Another way without regex:

$newurl = substr($url, 0, strpos($url,"#")); 
SpawnCxy
@Russell Dias,isn't it what OP wanted?
SpawnCxy
@SpawnCxy Indeed, I misread your solution. =)
Russell Dias
A: 

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

Andy Lester
While I agree wholeheartedly with the sentiment, this isn't really an answer.
Frank Farmer
Why are you telling me this?
Andy Lester