corbin Posted November 23, 2008 Share Posted November 23, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/133861-string-does-not-have-a-substring-in-it-in-1-regexp-p/ Share on other sites More sharing options...
ddrudik Posted November 23, 2008 Share Posted November 23, 2008 $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> Quote Link to comment https://forums.phpfreaks.com/topic/133861-string-does-not-have-a-substring-in-it-in-1-regexp-p/#findComment-697181 Share on other sites More sharing options...
corbin Posted November 23, 2008 Author Share Posted November 23, 2008 Nice! Gonna have to research parts of that one because I have no idea what was going on. lol Quote Link to comment https://forums.phpfreaks.com/topic/133861-string-does-not-have-a-substring-in-it-in-1-regexp-p/#findComment-697281 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.