I'm currently 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.
This is not a good way to match hyperlinks. It'll break if the links are already fully formed (eg 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 .
Add the non-greedy flag ?
also to the first .*
.
$pattern = "/www\.(.*?)\.(.*?)(\s|$)/";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.