A
A
Albert Ushakov2021-06-06 15:18:41
PHP
Albert Ushakov, 2021-06-06 15:18:41

How to add a condition to the regular expression "Is there any characters before the match"?

You need to make a regular expression that replaces hashtags with links.
Here is the code that does it:

$pattern = "/\#(\w+)/ui";
$text = preg_replace($pattern, '<a href="'.site_url().'?s=%23$1&bp_search=1&view=content" target="_blank">#$1</a>',$text);

The problem is that, for example, if you add an emoji, it will have the code "& # x1f601 (No spaces, the editor does not skip)" and the regular expression replaces this line.
How to make a condition to check if there is something before the # sign (Except for a space) and if there is , then do not add a link.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergo Zar, 2021-06-06
@fuck_ask

Here is /(?<![&])(?:\B)#(\w+)/iu
https://regex101.com/r/0tnI4B/1 (the g flag was set for clarity)
Ps if necessary, it will /(?<![&])#(\w+)/iucapture the "text#tag" https://regex101.com/r/1PUO2t/1 (the g flag was set for clarity )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question