1

I found a routine to create a html link when a link is found in a text

 <?php function makelink($text) { return preg_replace('/(http\:\/\/[a-zA-Z0-9_\-\.]*?) /i', '<a href="$1">$1</a> ', $text." "); } // works echo makelink ("hello how http://www.guruk.com "); // dont work echo makelink ("hello how http://www.guruk.com/test.php "); 

?>

as you see in the example, it works find with a domain only, not when there is a page or subdirectory is within that link.

Can you provide a solution for that function to work also with pages and subdirs?

thx chris

1

3 Answers 3

4

The characters ?=& are for urls with query strings. Notice that I changed the separator from / to ! because there a lot of slashes in your expression. Also note that you don't need A-Z if you are in case-insensitive mode.

return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." "); 
Sign up to request clarification or add additional context in comments.

Comments

0

Your regex should include forward slashes in its character class for the end of the url:

/(http\:\/\/[a-zA-Z0-9_\-\.\/]*?) /i 

That ought to do it.

Comments

0

Without RegEx:

<?php // take a string and turn any valid URLs into HTML links function makelink($input) { $parse = explode(' ', $input); foreach ($parse as $token) { if (parse_url($token, PHP_URL_SCHEME)) { echo '<a href="' . $token . '">' . $token . '</a>' . PHP_EOL; } } } // sample data $data = array( 'test one http://www.mysite.com/', 'http://www.mysite.com/page1.html test two http://www.mysite.com/page2.html', 'http://www.mysite.com/?go=page test three', 'https://www.mysite.com:8080/?go=page&test=four', 'http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive', 'ftp://test:[email protected]:21/pub/', 'gopher://mysite.com/test/seven' ); // test our sample data foreach ($data as $text) { makelink($text); } ?> 

Output:

<a href="http://www.mysite.com/">http://www.mysite.com/</a> <a href="http://www.mysite.com/page1.html">http://www.mysite.com/page1.html</a> <a href="http://www.mysite.com/page2.html">http://www.mysite.com/page2.html</a> <a href="http://www.mysite.com/?go=page">http://www.mysite.com/?go=page</a> <a href="https://www.mysite.com:8080/?go=page&test=four">https://www.mysite.com:8080/?go=page&test=four</a> <a href="http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive">http://www.mysite.com/?redir=http%3A%2F%2Fwww.mysite.com%2Ftest%2Ffive</a> <a href="ftp://test:[email protected]:21/pub/">ftp://test:[email protected]:21/pub/</a> <a href="gopher://mysite.com/test/seven">gopher://mysite.com/test/seven</a> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.