Page 1 of 1

Take links from a form

Posted: Fri Jul 02, 2010 2:22 pm
by xionhack
Hello. I have a form in my website where people will put their html code. What I want to do is to be able to take all the links in that html and swap them with something else. So that would be 2 processes, first get all the links and then swap them. For example

If i submit:

Code: Select all

<html>
Hello <br />
<a href="http://www.google.com" > Google</a>
<a href="http://www.yahoo.com" > Yahoo</a>
</html>

That would become

Code: Select all

<html>
Hello <br />
<a href="http://www.link_1" > Google</a>
<a href="http://www.link_2" > Yahoo</a>
</html>

Re: Take links from a form

Posted: Fri Jul 02, 2010 5:39 pm
by Jonah Bron
This should work if there is no direct relation to the link and it's replacement.

Code: Select all

$count = 1;
function rep_call($str) {
    global $count;
    return $str[0] . 'link_' . ($count++) . $str[2];
}
$text = preg_replace_callback('/(\<a href\=\")(.*?)(\">.*?\<\/a\>/i', 'rep_call', $text);

Re: Take links from a form

Posted: Wed Jul 07, 2010 6:04 pm
by xionhack
I havce a problem with this, lets say sometimes people dont write the links as <a href=.... but sometimes they might write <a id=something href=.... , so it wouldnt work in that case, how can i make it work for any case? thanks!

Re: Take links from a form

Posted: Wed Jul 07, 2010 9:17 pm
by Jonah Bron
Replace

Code: Select all

$text = preg_replace_callback('/(\<a href\=\")(.*?)(\">.*?\<\/a\>/i', 'rep_call', $text);
With

Code: Select all

$text = preg_replace_callback('/(\<a .*?href\=\")(.*?)(\".*?>.*?\<\/a\>/i', 'rep_call', $text);