Sercan
Sercan

Reputation: 325

Regex for linkifying urls

I'm trying to linkify URLs inside a text content. I know there are so many questions and answers for this purpose but I have a little bit different situation here.

What I want to do is converting this:

the best search engine is [out: http://google.com google].

into this:

the best search engine is <a href="http://google.com" rel="nofollow">google</a>.

or converting this:

the best search engine is [in: google].

into this:

the best search engine is <a href="http://mywebsite.com/google">google</a>.

What is the easiest way to do this in PHP for a newbie?

The best point I've reached is this:

$message = preg_replace("'(in: (.*))'Ui","(in: <a href=\"link.php?t=\\1\"><b>\\1</b></a>)",$message);

Upvotes: 1

Views: 39

Answers (2)

ssc-hrep3
ssc-hrep3

Reputation: 16069

You can use those two regular expressions:

\[in:\s*([^\[\]]*?)\]
\[out:\s*([^\[\]]*?)\s([^\[\]]*?)\]

Here is an example for the matching the groups in JavaScript (live test):

var regex1 = /\[in:\s*([^\[\]]*?)\]/g;
var regex2 = /\[out:\s*([^\[\]]*?)\s([^\[\]]*?)\]/g
var text = document.getElementById('main').innerHTML;
text = text.replace(regex1, '<a href="http://mywebsite.com/$1">$1</a>');
text = text.replace(regex2, '<a href="$1" rel="nofollow">$2</a>');

console.log(text);
<div id="main">
  the best search engine is [out: http://google.com google].
  the best search engine is [in: google].
</div>


And here the same in PHP:

<?php
$regex1 = "/\\[in:\\s*([^\\[\\]]*?)\\]/";
$regex2 = "/\\[out:\\s*([^\\[\\]]*?)\\s([^\\[\\]]*?)\\]/";
$text = 'the best search engine is [out: http://google.com google]. the best search engine is [in: google].';

$text = preg_replace($regex1, '<a href="http://mywebsite.com/$1">$1</a>', $text);
$text = preg_replace($regex2, '<a href="$1" rel="nofollow">$2</a>', $text);

echo $text;
?>

Live example in PHP Sandbox online

Upvotes: 1

Nicolas
Nicolas

Reputation: 7081

  • For the first one, you can use this regex: \[out:\s*([^\s]*)\s*(.*)\] and replace with <a href="\1" rel="nofollow">\2</a>.
  • For the second case, use \[in:\s*(.*)\], and replace with <a href="http://mywebsite.com/\1">\1</a>.

Here's some code to do it, using $result = preg_replace(pattern, substitution, input):

$result1 = preg_replace("/[out:\s*([^\s]*)\s*(.*)]/", '<a href="\1" rel="nofollow">\2</a>', $input);    
$result2 = preg_replace("/[in:\s*(.*)]/", '<a href="mywebsite.com\\1">\\1</a>', $input); 

Upvotes: 1

Related Questions