0

So i am making a very basic site where someone types in a box some text and it posts it into mysql.

Example:

Here is my post with a cool link - htt://www.coolness.com

The following script simply grabs the column wanted from the database and echos it on a line.

<?php
$con = mysql_connect("localhost","####","####");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("####", $con);

$result = mysql_query("SELECT * FROM posts");

while($row = mysql_fetch_array($result))
  {
  echo $row['post_content'];
  echo "<br />";
  }

mysql_close($con);
?>

The link is in plain text and instead I would like either php or javascript to write it as a hyperlink by adding the whole bit to it.

I've looked through examples, but nothing seemed to work when I tried to apply them.

Any tips would be great.

Isaac Boda
  • 21
  • 3
  • This link shows someone solving the same problem http://stackoverflow.com/questions/8027023/regex-php-auto-detect-youtube-image-and-regular-links – chris_code Jun 16 '12 at 16:27
  • This link shows someone solving the same problem http://stackoverflow.com/questions/8027023/regex-php-auto-detect-youtube-image-and-regular-links – chris_code Jun 16 '12 at 16:28

2 Answers2

1

Hope I understood what you meant:

Change to

while($row = mysql_fetch_array($result))
  {
  echo '<a href="' . $row['post_content'] . '">' . $row['post_content'] . '</a>';
  echo "<br />";
  }

What this code does, is that it prints the links inside <a> tags, which are links.

Matsemann
  • 18,825
  • 18
  • 54
  • 88
  • Correct, but not everything they post into the database will be a link. This would just make the whole post in mysql a link. Here is my post with a cool link - urladdress into Here is my post with a cool link - urladdress – Isaac Boda Jun 16 '12 at 16:16
  • Okey, now I think I understand what you meant. You could use a regular expression (regex) to find URLs in the text, and then surround those with the stuff. – Matsemann Jun 16 '12 at 16:20
1

Use preg_replace() in PHP. Pass it a regular expression for a URL, how you want that matched URL to be replaced, and then the string you pulled from your DB.

You want to turn "http://www.coolness.com" into "http://www.coolness.com'>http://www.coolness.com".

See this question for discussion on regexes for URL matching, and this piece of the PHP documentation for more on the preg_replace() function.

EDIT: SO seems to have had fun with my second line there! It should read:

You want to turn "http://www.coolness.com" into "<a href='http://www.coolness.com'>http://www.coolness.com</a>".

Community
  • 1
  • 1
Richard
  • 924
  • 6
  • 15