用字符串中的超链接替换花括号包裹的表达式

Replace curly braced wrapped expressions with hyperlinks in a string

我正在努力使用一些正则表达式来替换我从 API:

获得的新闻文章中的一些格式化表达式

我有一个包含一些内容的长字符串。在内容中有括号 ({}),其中包含某个公司及其公司实体编号——我想将它们转换为超链接。

输入:

{Company X Inc.|CVR-1-81287283} was recently acquired by {Company Z Inc.|CVR-1-34251568}

期望的输出:

<a href="companies/CVR-1-81287283">Company X Inc.</a> was recently acquired by <a href="companies/CVR-1-34251568">Company Z Inc.</a>

您的格式为

 { Company name | Company code}

您可以像上面的格式一样将正则表达式分成两部分,如下所示:

/\{([^\|]+)\|([^}]+)\}/
    ------   -------
  match       match
  company     company
  name        code

您可能会在 {|} 之前看到 \。这只是为了转义正则表达式元字符。 我们基本上匹配公司名称不属于 | 的所有字符和公司代码 } 之前的所有字符。

片段:

<?php

$str = '{Company X Inc.|CVR-1-81287283} was recently acquired by {Company Z Inc.|CVR-1-34251568}';

preg_match_all('/\{([^\|]+)\|([^}]+)\}/',$str,$matches);

$result = sprintf('<a href="companies/%s">%s</a>  was recently acquired by <a href="companies/%s">%s</a>',$matches[2][0],$matches[1][0],$matches[2][1],$matches[1][1]);

echo $result;

preg_replace() 是生成所需输出所需的全部内容。任何超出此范围的工作都太辛苦了。

代码:(Demo)

$string = '{Company X Inc.|CVR-1-81287283} was recently acquired by {Company Z Inc.|CVR-1-34251568}';

var_export(
    preg_replace('~\{([^|]+)\|([^}]+)}~', '<a href="companies/"></a>', $string)
);

输出:(如果您使用 echo 而不是 var_export(),您将看不到最外面的单引号)

'<a href="companies/CVR-1-81287283">Company X Inc.</a> was recently acquired by <a href="companies/CVR-1-34251568">Company Z Inc.</a>'

模式:

\{         #match a literal left curly brace
(          #start capture group #1
  [^|]+    #match one or more non-pipe characters
)          #end capture group #1
\|         #match a literal pipe
(          #start capture group #2
  [^}]+    #match one or more non-right-curly-braces
)          #end capture group #2
}          #match a literal right curly braces