TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Parsing URL in text (http://www.talkphp.com/advanced-php-programming/3240-parsing-url-text.html)

localhost 08-14-2008 12:27 PM

Parsing URL in text
 
Hello,

I have paragraphs of text in a database, and I am trying to convert the url's to proper links, e.g. :
This site Google is cool
would be : This site Google is cool

and the same if they had http:// on.

So far my code isn't working, so please I would be grateful if someone could help me achieve above.

Many Thanks,

Steven Gibbons

PHP Code:

if(!empty($data)) {
$url mysql_real_escape_string($_POST['url']);
$text preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@''<a href="$1">$1</a>'$url);
echo 
$text;



delayedinsanity 08-14-2008 01:35 PM

PHP Code:

$this->_string preg_replace('~((https?|ftp)\://[a-z0-9+_-]+(\.[a-z0-9+_-]+)*(/([a-z0-9+_-]\.?)+)*/?(\?[a-z+&_.-][a-z0-9;:@/&%=+$_.-]*)?(#[a-z_.-][a-z0-9+_.-]*)?)~is''<a href="$1">$1</a>'$this->_string); 

Has been working for me... doesn't parse the URLs title like vBulletins parser, but I still think it's a good start. ;-) Looks for web or ftp protocols, handles top level and sub-domains with ease, with any number of sub-directories, a query string, or an anchor.
-m

localhost 08-14-2008 01:42 PM

Thanks for your reply. I will give it a go.

localhost 08-14-2008 01:47 PM

Thanks for your reply. The only problem I am having now is it only works with http:// not just www.

Thanks,

Steve

delayedinsanity 08-14-2008 05:51 PM

Well, I suppose you could do this:

PHP Code:

$string preg_replace('~(((https?|ftp)\://)?(www\.)?[a-z0-9+_-]+(\.[a-z0-9+_-]+)*(/([a-z0-9+_-]\.?)+)*/?(\?[a-z+&_.-][a-z0-9;:@/&%=+$_.-]*)?(#[a-z_.-][a-z0-9+_.-]*)?)~is''<a href="$1">$1</a>'$string); 

I would actually consider this a fairly good regular expression to learn from, because although it looks complex to those who are new or completely foreign to regexps, it's actually a really easy regexp to break down once you start learning how they work - probably just as easy to modify and optimize as well, I just put it together in a rather quick fashion a while back and haven't touched it since.

If you're interested;

TalkPHP - Search Results
Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
Regular Expression Library
Regular Expressions Cheat Sheet (V2) - Cheat Sheets - Added Bytes
-m


All times are GMT. The time now is 02:19 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0