用字符串中的超链接替换大括号括起来的表达式

问题描述

我正努力使用一些正则表达式来替换我从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/$2">$1</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