Jump to content

String does not have a substring in it... In 1 regexp ;p.


corbin

Recommended Posts

OK, I have a noob question ;p.

 

 

I'm trying to replace all <a href="blah">bleh</a> With <a href="/blah>bleh</a>, but I only want to do it if blah does not start with https?://.  Seemed simple enough when I thought about it, but then I couldn't figure out how to do that.  I know how to do it in multiple statements, but is there a faster way than this ghetto trash?:

 

 

<?php

echo preg_replace('/<([^>]+)(href|src|action)="([^"]+)"/e', "replace_links(\"\\1\", \"\\2\", \"\\3\")", $input);

function replace_links($one, $two, $three) {
if(preg_match('/^(?:http|https)+:\/\//', $three)) return '<'.$one.$two.'="'.$three.'"';
return '<'.$one.$two.'="/'.$three.'"';
}

 

 

I guess I could assume a link could contain anything except a colon....

 

/<([^>]+)(href|src|action)="([^:]+?)"/

 

 

 

Just hoping someone can come up with a better regexp.

$html=preg_replace('#<a\s[^>]*\bhref="(?=(??!/|https?://)[^"])+)#i','$0/',$html);

 

haystack:

<a href="blah">bleh</a> With <a href="/blah">bleh</a>
<a href="blah/">bleh</a> With <a href="/blah">bleh</a>
<a href="http://blah">bleh</a> With <a href="https://blah">bleh</a>

 

output:

<a href="/blah">bleh</a> With <a href="/blah">bleh</a>
<a href="/blah/">bleh</a> With <a href="/blah">bleh</a>
<a href="http://blah">bleh</a> With <a href="https://blah">bleh</a>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.