D
D
Dmitry STEM2018-04-24 22:35:39
Regular Expressions
Dmitry STEM, 2018-04-24 22:35:39

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|Тестовая страница]

etc. They need to be replaced with (example): I read what and how in regular expressions, googled it, but it still doesn’t work ... I compiled a regular expression using some service, but it doesn’t fit ...
<a href="ссылка/id1">Паша</a>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry STEM, 2018-04-24
@STEM1

Answered on stackoverflow.
/\[(.+)\|(.+)\]/U

M
Moskus, 2018-04-24
@Moskus

The service for compiling regular expressions will not replace understanding the syntax.
Search \[([^|]+)|([^\]]+)\]to replace with<a href="https://vk.com/$1">$2</a>

I
Immortal_pony, 2018-04-24
@Immortal_pony

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;
}

V
Vitaly Musin, 2018-04-24
@vmpartner

https://regexr.com/3ofjs

(.+)\s+?\[(.+)\|(.+)\]
Бла бла бла [durov|Паша]
$1 <a href="https://vk.com/$2">$3</a>

5adf92d6482a9850821058.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question