Jump to content

Parsin URL from string then convert to hyperlink....


Sonic88

Recommended Posts

Her everyone! This is my first time posting here. Ive been doing some PHP work and I have run into a little problem

 

I have a basic news script that stores a news post as a string in a database. Anyways, my client will sometimes put urls within the news post and I would like to parse those out and replace them with a hyperlink. It doesnt have be fancy, basically just put anchor tags around the url and put the url into the href.

Ive been looking for a while and cant seem to figure this out. Any help is greatly appreciated!

 

here is the code i have tried from somewhere else but it only works sometimes but usually not:

<?php
require_once './inc/dbconnect.php';//MySQL connect file
@mysql_select_db($dbname) or die( "Unable to select database");//select database
$query = "SELECT body, title, DATE_FORMAT(date_created, '%W %M %D %Y') as date_created FROM news ORDER BY id DESC";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
$date = $row['date_created'];
echo '<b><p class="date">' . $date . '</b>   <u>' . $row['title'] . '</u><br />';
//parse out web addresses within news message
$body = ereg_replace("http://([a-zA-Z0-9./-]+)$", "<a href=\"\\0\">\\0</a>", $row['item']);
echo '<blockquote>' . $row['body'] . '</blockquote>';
}
?>

Hmm well it doesnt seem to be working at all now. And I notcecd that the variable printed was not the one changed by the ereg function. I have changed that to print the $body variable and it still does not work. THe code I used was found on a site a few months ago. Does anyone have a better way to do it? It seems like a routine process, but I just cant seem to find any info on it.

  • 2 weeks later...

It may help if you were pulling 'item' from the DB. Try this for your query:

 

<?php
require_once './inc/dbconnect.php';//MySQL connect file
@mysql_select_db($dbname) or die( "Unable to select database");//select database
$query = "SELECT body, title, item, DATE_FORMAT(date_created, '%W %M %D %Y') as date_created FROM news ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error()); // incase of an error

while($row = mysql_fetch_array($result)){
$date = $row['date_created'];
echo '<b><p class="date">' . $date . '</b>   <you>' . $row['title'] . '</you><br />';
//parse out web addresses within news message
$body = ereg_replace("http://([a-zA-Z0-9./-]+)$", "<a href=\"\\0\">\\0</a>", $row['item']);
echo '<blockquote>' . $body . '</blockquote>';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.