如何匹配子字符串并将其转换为超链接?

How to match a substring and convert it to a hyperlink?

我的申请需要帮助。我想用正则表达式匹配一个子字符串,然后提取它。有我的代码:

$text = getTranslation('end_date', $translation);
if (strstr($text, "/@:url[.*?]/")){
    $text = str_replace("/@:url[.*?]/", "<a href='$promo->wabsiteUrl'>ANYTHING</a>", $text);
}
echo $text;

getTranslation() 是我创建的一种方法,用于在我的对象 $translation 中获取翻译项 end_date。问题是我对正则表达式很糟糕。我尝试了一些东西,但它不起作用。

这是变量 $text 的内容:@:url[Click here] to find out where to buy Razer inc.(来自 $translation

@:url 等于我的推广网站,然后 [] 里面是我的 <a href=""></a> 元素的文本。

所以,我需要寻找 @:url[ANYTHING] 然后提取 ANYTHING 来创建这个 <a href="">ANYTHING</a>

我有点迷茫所以这是我的理解:

preg_replace("#/@:(.*?)\[(.*?)\]/#", "<a href=\"\"></a>", $text);

这将匹配 /@:<something>[anotherthing]/ 形式的字符串并将其替换为 <a href="something">anotherthing</a>

更新:

preg_replace("#/@:url\[(.*?)\]/#", "<a href=\"".$promo->websiteUrl."\"></a>", $text);

这将匹配 /@:url[thing]/ 形式的字符串并将其替换为 <a href="your promo url in that variable">thing</a>

如果您不需要 // 那么您可以将正则表达式更改为 "#@:url\[(.*?)\]#"

你能试试这个吗?

if(preg_match_all('%@:url\[(.*?)\]%i', $text, $matches)){
    print_r($matches);
}