Take links from a form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Take links from a form

Post 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>
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Take links from a form

Post 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);
xionhack
Forum Contributor
Posts: 100
Joined: Mon Nov 10, 2008 9:22 pm

Re: Take links from a form

Post 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!
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Take links from a form

Post 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);
Post Reply