R
R
rusgayfer2018-02-15 21:13:05
PHP
rusgayfer, 2018-02-15 21:13:05

How to convert VK text links into hyperlinks?

I get records from the VK API and there are links of this kind

[id+++|name] - для пользователей 
[club++++|name] - для групп и пабликов

How to make through preg_replace into regular links of the form<a href="ссылка" target="_blank">текст</a>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
riot26, 2018-02-15
@rusgayfer

<?php
$text = '
[Оля Старицына|id8888], [id555|Надежда Созыкина], [id665|Катя Иванова]
';

$re = '/\[((id|club)\d+)\|([^\]]+)\]/';
$replacement = '<a href="https://vk.com/$1" target="_blank">$3</a>';

$text = preg_replace($re, $replacement, $text);
echo $text;

Conclusion:
[Оля Старицына|id8888], <a href="https://vk.com/id555" target="_blank">Надежда Созыкина</a>, <a href="https://vk.com/id665" target="_blank">Катя Иванова</a>

A
Andrey Nikolaev, 2018-02-15
@gromdron

Am I confused or is this what you wanted?

$regex = "#\[id([0-9]+)\|([^\]]+)\]#";
$testString = 'Как же хорого побывать в группе [id123|Привет Мир!]';

// Напечатает: Как же хорого побывать в группе <a href="123" target="_blank">Привет Мир!</a>
echo preg_replace($regex, '<a href="$1" target="_blank">$2</a>', $testString);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question