Re: Parsing HTML href-Attribute
| From: | Shawn McKenzie | Date: | Fri, 16 Jan 2009 20:46:37 +0000 |
| Subject: | Re: Parsing HTML href-Attribute | ||
| References: | 1 2 3 4 5 6 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-286525@lists.php.net to get a copy of this message | ||
>> I believe the OP wanted to leave already-absolute paths alone
>> (i.e., only convert relative paths). The regex does not take into
>> account fully-qualified URLs (i.e.,
>> http://www.google.com/search?q=php) and it does not
>> determine if a
>> given path is relative or absolute. He was wanting to take the href
>> attribute of an anchor tag and, **IF** it was a relative path, turn
>> it into an absolute path (meaning to append the relative path to
>> the absolute path of the current script).
>
> That's exactly what this regex does :-) The (?!$prefix) negative
> lookahead assertion fails the match if it's already an absolute URL.
>
>> That was my understanding. Perhaps you saw it differently, but I
>> don't believe your pattern is enough to accomplish what the OP was
>> asking for--hence "a lot" of code was in my reply. ;)
>>
>> Believe me, I'm the first guy to hop on the "do it with a regex!"
>> bandwagon... but there are just some circumstances where regex
>> can't do what you need to do (such as more-than-superficial
>> contextual logic).
>>
>> HTH,
>>
>>
>> // Todd
>
Ahh, but you uncovered a problem for me if the href contains an
absolute URL that doesn't contain the prefix. Here's the fix:
$html =
preg_replace("|(href=['\"]?)(?!http(?:s)?://)[/]?([^>'\"\s]+)(\s)?|",
"$1http://www.example.com/2$3", $html);
--
Thanks!
-Shawn
http://www.spidean.com