如何格式化[url=][/url]代码或短代码上自定义构建的网站


How to format [url=][/url] code or shortcode on a custom built website?

我需要做一些功能或短代码来格式化这些类型的链接。

我在一些网站和解析数据从json格式和内部的数据有链接代码像这样的文本工作。

所以我在json文件中得到的是:

[url=http://store.steampowered.com/app/901583/]GTA IV: Complete Edition[/url] includes Grand Theft Auto IV and Episodes from Liberty City.

所以我使用:

$json = file_get_contents('link file'); //to get json file
$file = json_decode($json, true); //to retrieve data as an array

我得到的是:

Array
(
[6516] => Array
    (
        [success] => 1
        [data] => Array
            (
                [name] => Grand Theft Auto IV: Complete Edition
                [purchase_text] => [url=http://store.steampowered.com/app/901583/]GTA IV: Complete Edition[/url] includes Grand Theft Auto IV and Episodes from Liberty City.
            )
    )
)

代码太大,所以我剪掉了不相关的文本

然后我使用:

$pobj[$package]['data']['purchase_text']; //where $package is package id(the number in array)

但是这个文本对于每个json文件都是不同的并且可能有多个url所以我需要某种通用的解决方案

那么我如何得到这些url链接格式在我的网站作为正常链接?短代码之类的?

您可以使用像

这样的正则表达式

'[url=(.*)'](.*)'['/url']

这将拉出链接和标题:

preg_match('|'[url=(.*)'](.*)'['/url']|', $string, $matches);

$matches[1]表示链接,$matches[2]表示标题:

echo '<a href="' . $matches[1] . '">' . $matches[2] . '</a>';

作为对评论的回应,让我们变得更复杂一点:

这个正则表达式将更精确,并匹配字符串中的多个url:

'[url=(https?:'/'/?['da-z'.-]+'.[a-z'.]{2,6}(['/'w '.-]*)*'/?)'](.*?)'['/url']