用字符串中的HTML链接替换类似Markdown的链接 [英] Replace Markdown-like links with HTML links in a string

查看:69
本文介绍了用字符串中的HTML链接替换类似Markdown的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串形式

"Look at this [website]{http://www.stackoverflow.com} 
or at this [page]{http://www.google.com}"

我想用PHP解析它们

"Look at this <a href='http://wwwstackoverflow.com'>website</a> 
or at this <a href='http://www.google.com'>page</a>"

我该怎么做?

我虽然要使用str_replace(),但是我不知道如何在方括号[]之间获得字符串.

I though about using str_replace()but I dont know how to get the string between the brackets [].

编辑[26.08.2016] :答案使用带有正则表达式的PHP preg_replace方法.我在这里不明白给出的答案,但是它起作用了,所以我很高兴,但是现在我发现了免费教程,该教程可以教您如何使用正则表达式.我发现它非常有帮助.尤其是当有人想为类似的情况写自己的正则表达式时.

Edit[26.08.2016]: The answer uses the PHP preg_replace method with Regular Expression. I didnt understand the given answer here, but it worked so I was happy But now I found this free tutorial that teaches you how to use Regular Expression. I found it very helpful. Especially when one wants to wrtie his own Regular Expression for a similar case.

推荐答案

尝试使用preg_replace

$str="Look at this [website]{http://www.stackoverflow.com} or at this [page]{http://www.google.com}";

echo preg_replace('/\[(.*?)\]\{(.*?)\}/', "<a href='$2'>$1</a>", $str);

输出:

Look at this <a href='http://www.stackoverflow.com'>website</a> or at this <a href='http://www.google.com'>page</a>

工作示例: https://3v4l.org/jLbff

这篇关于用字符串中的HTML链接替换类似Markdown的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆