简体   繁体   English

PHP 用锚标记替换字符串中的 URL

[英]PHP Replace URLs in string with Anchor tag

I'm trying to parse a string that contains links in it.我正在尝试解析一个包含链接的字符串。 I'm happy to specify the format that they come across in, however normal HTML tags are being stripped out in transit.我很高兴指定它们遇到的格式,但是普通的 HTML 标签在运输过程中被剥离。

I'm suggesting the following format:我建议采用以下格式:

[url=https://test.com]my link[/url]

becomes:变成:

<a href="https://test.com" target="_blank">my link</a>

with no other attributes necessary.无需其他属性。

I have the following preg replace but it's not working我有以下 preg 替换,但它不工作

$result = preg_replace("/\[\burl\b=[1-9a-zA-Z:\.\-\/_]*?[\]]*?\[\/\burl\b\]/", "<a href='$1' target='_blank'>$2</a>", $str);

As soon as I try to get the link/text when building the regex I fall down.一旦我在构建正则表达式时尝试获取链接/文本,我就会崩溃。

Any help/simplification/other ideas greatly appreciated!非常感谢任何帮助/简化/其他想法!

You may consider using您可以考虑使用

preg_replace('~\[url=([^][\s]+)](.*?)\[/url]~s', "<a href='$1' target='_blank'>$2</a>", $text)

See the PHP demo and the regex demo .请参阅PHP 演示正则表达式演示

Details细节

  • \[url= - a [url= substring \[url= - [url= substring
  • ([^][\s]+) - Group 1 ( $1 ): any 1 or more characters other than [ , ] and whitespace ([^][\s]+) - 第 1 组 ( $1 ):除[ , ]和空格之外的任何 1 个或多个字符
  • ] - a ] char ] - 一个]字符
  • (.*?) - Group 2 ( $2 ): any zero or more characters, as few as possible (.*?) - 第 2 组 ( $2 ):任何零个或多个字符,尽可能少
  • \[/url] - a [/url] substring. \[/url] - 一个[/url] ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM