开发者

PHP regular expressions - replacing text with hyperlinks

I'm c开发者_StackOverflow中文版urrently working on some bespoke blog software. Under the management panel a user may create a post and PHP should then parse any text that matches my pattern and replace it with a live hyperlink accordingly. It works well for simple posts, however when a large post is given the the hyperlink is created with much more than the text link and extends to a whole paragraph of text.

Here's my PHP:

function TextToLinks($input)
{
    $pattern = "/www\.(.*)\.(.*?)(\s|$)/";
    return preg_replace_callback($pattern, "Utilities::LinksCallback", $input);
}

function LinksCallback($matches)
{
    return "<a href='http://{$matches[0]}'>{$matches[0]}</a>";
}

I can't work out how to make the pattern more strict.

Thanks for any help.


Add the non-greedy flag ? also to the first .*.

$pattern = "/www\.(.*?)\.(.*?)(\s|$)/";


This is not a good way to match hyperlinks. It'll break if the links are already fully formed (e. g. the poster already put http:// in front of it, and it'll miss all links that don't start with www..

If that's not a problem, you might get away with /\bwww\.(\S*)\.(\S*)\b/.

\S only allows non-whitespace characters to match, and \b assert that the match starts/ends at a word boundary.

For more background information, read this blog post by Jan Goyvaerts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜