Answer the question
In order to leave comments, you need to log in
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);
#[email protected]
@asfgas#asgasg
@[email protected]
#asfasf#asgas
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.
Answer the question
In order to leave comments, you need to log in
I don't really understand what you need but:
// Удалить собаку
$tag = preg_replace("/@/ism", "", $tag);
// Удалить собаку если это первый символ
$tag = preg_replace("/^@/ism", "", $tag);
//поставить пробел перед собакой если его нет
$tag = preg_replace("/@/ism", " @", $tag);
$tag = str_replace("@", "@", $tag, $gav);
$tag = str_replace("#", "#", $tag, $re);
if($gav > 0 && $re > 0){
// есть оба тега, один удалить
}
elseif($gav > 1){
// собаки две, одну удалить
}
elseif($re > 1){
// решётки две, одну удалить
}
else{
// всё в порядке, действия по дефолту
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question