与 PHP 中提供的文本链接

Linkify with provided text in PHP

我个人对 preg_replace 不是很在行,如果可能需要一些帮助。

我想链接一个字符串并允许一个可选的文本参数。示例:

Input: [[http://www.example.com/path/to/file.ext]]

Output: <a href="http://www.example.com/path/to/file.ext">http://www.example.com/path/to/file.ext</a>


Input: [[http://www.example.com/path/to/file.ext "click here"]]

Output: <a href="http://www.example.com/path/to/file.ext">click here</a>

我怎样才能做到这一点(如果可能,使用 preg_replace)?

提前谢谢你。

试试这个 regx,你想匹配 [[stuff]],对吧?

 /\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/

https://regex101.com/r/pT4bL1/1

我可以帮助您创建链接,但不知道您是如何创建它们的。例如,将 preg_match 与第 3 个参数一起使用,您将拥有 [[]] 中的部分,然后只需执行

  if( preg_match('/\[\[(?P<link>[^\s]+)\s(?P<text>[^\]]+)\]\]/', '[[http://www.example.com/path/to/file.ext "click here"]]', $match ) ){
      echo '<a href="'.$match['link'].'">'.$match['text'].'</a>';
   }

解释regx

  • \[\[ - 只是 [[
  • (?P<link>[^\s]+) - (?P<name>..,) 被命名为捕获组 [^\s]+ 除了 space.
  • \s一个space
  • (?P<text>[^\]]+) 除了 [^\]]+ 除了 ]
  • 与上面相同
  • \]\] - 结尾]]