【问题标题】:Replace Markdown-like links with HTML links in a string用字符串中的 HTML 链接替换类似 Markdown 的链接
【发布时间】:2020-06-16 09:33:26
【问题描述】:

我有一个表单字符串

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

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

【问题讨论】:

  • 使用this。不要重新发明轮子。 注意:链接的语法略有不同。
  • @Script47:这不是 相当 markdown 语法。链接是[Title](http://example.com)。他必须用() 替换{} 才能使用它。
  • @Script47 不幸的是,它不是 相当 Markdown。亚当,你真的确实使用现有的标记语言怎么样?
  • 用正则表达式和preg_replace,我猜
  • @Rocket 哈哈。连重点都一样……

标签: php


【解决方案1】:

试试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

【讨论】:

    【解决方案2】:

    这可以通过使用preg_replace 轻松实现:

    $pattern = "/(\\[([^\\]]+)\\]\\{([^\\}]+)\\})/";
    $replacement = '<a href="$3">$2</a>';
    $finalStr = preg_replace($pattern, $replacement, $yourString);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2015-09-10
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多