W
W
wolfak2015-09-15 13:14:08
PHP
wolfak, 2015-09-15 13:14:08

Regular expressions for generating hashtags in PHP #2?

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?
PS
I think that you need to do some kind of check-condition with if, something like:
If there are several #@ or ## or @# or @@ then there should be a space between each of them, otherwise nothing should be replaced. But I can’t write such a condition due to the fact that I don’t know regular expressions well.

and one more question. Can you tell me from the code above for redirecting links through the gateway, how to make sure that local links are not replaced? Thank you.
Link to old version of the question:
Regular expressions for generating hashtags in PHP?
Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Optimus, 2015-09-15
Pyan @marrk2

I don't really understand what you need but:

// Удалить собаку
$tag = preg_replace("/@/ism", "", $tag);
// Удалить собаку если это первый символ
$tag = preg_replace("/^@/ism", "", $tag);
//поставить пробел перед собакой если его нет
$tag = preg_replace("/@/ism", " @", $tag);

U.P.
$tag = str_replace("@", "@", $tag, $gav);
$tag = str_replace("#", "#", $tag, $re);
if($gav > 0 && $re > 0){
// есть оба тега, один удалить
}
elseif($gav > 1){
// собаки две, одну удалить
}
elseif($re > 1){
// решётки две, одну удалить
}
else{
// всё в порядке, действия по дефолту
}

Well, in fact, there can be 3.4 or more dogs or bars, and then it will also satisfy the conditions, but it will be necessary to remove more than one, well, you yourself will think how you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question