perf
perf

Reputation: 11

URL replacing regex

I'm trying to make an url that adds a / to all hrefs and srcs in a string. It should only add a / to urls that don't have a http:// at their beginning and that don't have / yet also.

If we have this:

<a href="ABC">...
<img src="DEFG">...
<a href="/HIJ">...
<a href="http://KLMN">...

The results should be something like this:

<a href="/ABC">...
<img src="/DEFG">...
<a href="/HIJ">...
<a href="http://KLMN">...

This is what i've come up till now:

&(href|src)="?!(\/|http::\/\/)(.+)"

And the replace would be

$1="/$2"

It isn't working, though.

Upvotes: 0

Views: 181

Answers (3)

Gumbo
Gumbo

Reputation: 655239

Maybe it suffices to change just the base URI with the base element:

<base href="/">

Now the base URI path is / instead of the path of the current document’s URI. But note that this affects all relative URIs and not just those with a relative URI path.

Upvotes: 1

Pindatjuh
Pindatjuh

Reputation: 10526

This will match tags with href or src in it, and the first group contains the adress.

(<[^<]*?(?:href|src)=")(?!http|/)(.+?)("[^<]*?>)

And replace with:

$1/$2$3

Upvotes: 0

SoapBox
SoapBox

Reputation: 20609

$str = preg_replace('/(href|src)="([^\/][^:]*)"/', '\1="/\2"', $str)

This will do what you ask, but has a little exception that any string containing a colon (:) will not get a "/" added. That allows it to easily handle http://, ftp://, etc, but also won't work for something like "abcd:efgh".

Upvotes: 0

Related Questions