Swaping links

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

Swaping links

Post by xionhack »

Hello. I have a questions that I think its pretty much about regular expresions. I have this code:

Code: Select all

function create_link($matches) {
  // link_id should be an auto-increment field
  $insert = mysql_query(sprintf("INSERT INTO links ( link_url ) VALUES ( '%s' )", $matches[1]));
  
  return '<a href="' . mysql_insert_id() .'">'. $matches[2] .'</a>';
}

// File name, could be a url
$file = 'file.html';

if (file_exists($file)) {
  $content = file_get_contents($file);
  
  // Regex replace string
  $pattern = '/<a href="([^"]+)">([^<]+)<\/a>/s';
  $content = preg_replace_callback($pattern, 'create_link', $content);

  echo $content;
}
What that does, is that it checks for all the links in a page, saves the links in a database and then swap the link address with the id of that link in the database. The problem that i have is that the code works when the link is just "<a href="" ></a>" but if the <a> tag has an attribute, then it wont work. i.e <a href="" id=""></a> OR <a id="" title="" href=""></a>
Post Reply