Re: Parsing HTML href-Attribute

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Edmund,

You want a regex that looks something like this:

$result = preg_replace('%(href=)("|\')(?!c:/)(.+?)("|\')%',
'\1\2c:/my_absolute_path\3\4', $subject);

This example assumes that your absolute path begins with "c:/". You would
change this to whatever suits. You would also change "c:/my_absolute_path"
to be whatever appropriate value indicates the absolute path element that
you want to prepend.

Note: this will NOT accound for hrefs that are not encapsulated in either '
or ". The problem being that while you can probably predictably how the
substring starts, it would be more difficult to determine how it ends,
unless you can provide a white list of file extensions for the regex (ie, if
you know you only ever link to, for example, files with .php and or .html
extensions). In that case, you probably could alter the regex to test for
these instead of a ' or ".

M is for Murray


On Fri, Jan 16, 2009 at 8:13 AM, Edmund Hertle <
edmund.hertle@xxxxxxxxxxxxxxx> wrote:

> Hey,
> I want to "parse" a href-attribute in a given String to check if there is a
> relative link and then adding an absolute path.
> Example:
> $string  = '<a class="sample" [...additional attributes...]
> href="/foo/bar.php" >';
>
> I tried using regular expressions but my knowledge of RegEx is very
> limited.
> Things to consider:
> - $string could be quite long but my concern are only those href attributes
> (so working with explode() would be not very handy)
> - Should also work if href= is not using quotes or using single quotes
> - link could already be an absolute path, so just searching for href= and
> then inserting absolute path could mess up the link
>
> Any ideas? Or can someone create a RegEx to use?
>
> Thanks
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux