Answer the question
In order to leave comments, you need to log in
How to write a regular expression to replace text with a link (vk)?
There are inserts in the text from VK. Examples:
[id1|Паша][club1231|Test][club1231222|Тестовая страница]
<a href="ссылка/id1">Паша</a>
Answer the question
In order to leave comments, you need to log in
The service for compiling regular expressions will not replace understanding the syntax.
Search \[([^|]+)|([^\]]+)\]
to replace with<a href="https://vk.com/$1">$2</a>
You can do it without any regulars.
The implementation is simplified, you can modify it yourself, taking into account possible errors - the symbol "|" is missing inside the shortcode or the absence of an opening/closing bracket.
function replaceShortcodesWithLinks($text) {
$shotcodeQuantity = min([substr_count($text, "["), substr_count($text, "]")]);
$offset = 0;
for ($i=0; $i<$shotcodeQuantity; $i++) {
$openBracePos = strpos($text, "[", $offset);
$closeBracePos = strpos($text, "]", $openBracePos);
$shortcode = substr($text, $openBracePos+1, $closeBracePos-$openBracePos-1);
list($id, $title) = explode("|", $shortcode);
$link = "<a href='https://vk.com/{$id}'>{$title}</a>";
$text = substr($text, 0, $openBracePos) . $link . substr($text, $closeBracePos+1);
$offset = $closeBracePos + strlen($link);
}
return $text;
}
https://regexr.com/3ofjs
(.+)\s+?\[(.+)\|(.+)\]
Бла бла бла [durov|Паша]
$1 <a href="https://vk.com/$2">$3</a>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question