One of the fields in our PHP page is a description - occasionally there are website links included. However, when pulling this data from the database table the links remain non-clickable. How can I parse text from database table as HTML in final rendered PHP page? Thanks!
3 Answers
Do you mean something like this?
<?php
echo "<a href='$linkLocation'>$linkName</a>";
?>
[Edit]
Server-side you could transform the orginal text ($det[9]) like this (based on this SO question):
<div id="text"><?php
echo preg_replace_callback(
'/http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/',
create_function(
'$matches',
'return \'<a href="http://\'. $matches[1] .\'">\'. $matches[1] .\'</a>\';'
),
$det[9]
);
?></div>
[Edit: merged the original code from your comment] [Edit: fixed typo]
7 Comments
JoeW
Hmmm, not really. It is not code as such - it is simply text input from a form which may sometimes include a website address such as stackoverflow.com - but I would like that text to be rendered as a URL when pulled from the table into the PHP page. The table type is currently varchar(1500)
Jochem
Ah, well then you have to decide on what you define what has to be converted to url and what hasn't.
http://www.google.com? Sure. "www.stackoverflow.com"? Probably. Stackoverflow.com? Bit.ly? someword.anotherword? It's tricky! After having decided, a regexp-string-replace, at either server or client side, should do.JoeW
A full standard URL as
http://www.google.com is the only text to convert to a clickable URL. Hmmm, a regexp-string-replace, at either server or client side? You're going to need to talk me through that - sorry!JoeW
OK, so here is the code for pulling the database table text to the page... can you show me where to insert your code (sorry to need to be spoon fed this!):
<div id="text"><?php echo $det[9];?></div>JoeW
Unfortunately that returned an error... from the following line:
return \'<a href="http://\'. $matches[1] .\'">\'. $matches[1] .\'</a>\';' Parse error: syntax error, unexpected T_RETURN in /home/mydomain/public_html/project.php on line 112 |
Are your text stored as HTML or is it just a text containing URLs?
1 Comment
JoeW
It is just text containing URLs and other text. Currently the table is 'varchar(1500)'.
Follow these steps
- Change the db feild to text,
- While inserting data convert the html entities and escape the quotes.
- while retrieving do the reverse process and you can retrieve data in html format this way
1 Comment
JoeW
This sounds sensible, but only some of the text will be urls. For example:
The website I am using in this text is http://www.google.com
href=""atttribute. could you post some of your code?