Jump to content

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


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>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.