我正在尝试将文本内容中的网址链接起来。我知道为此目的有很多问题和答案,但我在这里有一些不同的情况。
我想要做的是转换它:
the best search engine is [out: http://google.com google].
进入这个:
the best search engine is <a href="http://google.com" rel="nofollow">google</a>.
或转换它:
the best search engine is [in: google].
进入这个:
the best search engine is <a href="http://mywebsite.com/google">google</a>.
对于新手来说,在PHP中执行此操作的最简单方法是什么?
我达到的最好点是:
$message = preg_replace("'(in: (.*))'Ui","(in: <a href=\"link.php?t=\\1\"><b>\\1</b></a>)",$message);
答案 0 :(得分:1)
\[out:\s*([^\s]*)\s*(.*)\]
并替换为<a href="\1" rel="nofollow">\2</a>
。 \[in:\s*(.*)\]
,并替换为<a href="http://mywebsite.com/\1">\1</a>
。使用$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);
答案 1 :(得分:1)
您可以使用这两个正则表达式:
\[in:\s*([^\[\]]*?)\]
\[out:\s*([^\[\]]*?)\s([^\[\]]*?)\]
以下是在JavaScript(实时测试)中匹配组的示例:
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>
在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;
?>