gpt4 book ai didi

php - 将类似 Markdown 的链接替换为字符串中的 HTML 链接

转载 作者:行者123 更新时间:2023-11-28 03:07:06 25 4
gpt4 key购买 nike

我有一个以下形式的字符串

"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(),但我不知道如何获取括号[]之间的字符串。

编辑[2016年8月26日]:答案使用 PHP preg_replace 方法和正则表达式。我不明白这里给出的答案,但它有效,所以我很高兴但现在我发现 this免费教程,教您如何使用正则表达式。我发现它非常有帮助。特别是当一个人想为类似的情况编写自己的正则表达式时。

最佳答案

尝试使用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

关于php - 将类似 Markdown 的链接替换为字符串中的 HTML 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60516784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com