W
W
wolfak2015-09-02 10:23:40
PHP
wolfak, 2015-09-02 10:23:40

Regular expressions for generating hashtags in PHP?

Good time of the day. There was a need to create hashtags for the site.
With regular expressions, everything is not always smooth for me, so I turned to the Internet for help and, following the example, made the following expressions for hashtags and external links:

$Post_Text = preg_replace("~(http|https|ftp|ftps)://(.*?)(\s|\n|[,.?!](\s|\n)|$)~", '<noindex><nofollow><a href="http://site.ru/link=$2" target="_blank">$2</a></nofollow></noindex>$3', $Post_Text);
$Post_Text = preg_replace("/#([\S]+)/", "<a href=\"http://site.ru/posts&search=\\1\">#\\1</a>", $Post_Text);
$Post_Text = preg_replace("/@([\S]+)/", "<a href=\"http://site.ru/\\1\">@\\1</a>", $Post_Text);

But these expressions have a huge minus. If you write such tags, they will be displayed with an error:
#[email protected]
@asfgas#asgasg
@[email protected]
#asfasf#asgas

How to correct these expressions or what conditions to add so that there are no such errors and everything works? Thanks for the help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Inchin ☢, 2015-09-02
@In4in

Design [^]to help you.

ok, click here
$Post_Text = preg_replace("/#([^\b#@]+)/", "<a href='http://site.ru/posts&search=$1'>#$1</a>", $Post_Text);
$Post_Text = preg_replace("/@([^\b#@]+)/", "<a href='http://site.ru/$1'>@$1</a>", $Post_Text);

H
heartdevil, 2015-09-02
@heartdevil

$Post_Text = preg_replace('/(?:^|\s)#([\S]+)/gim', "<a href=\"http://site.ru/posts&search=\\1\">#\\1</a>", $Post_Text);
$Post_Text = preg_replace('/(?:^|\s)@([\S]+)/gim', "<a href=\"http://site.ru/\\1\">@\\1</a>", $Post_Text);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question