Php 与preg#u匹配';有可能有相同的样式和不同的替换品吗?

Php 与preg#u匹配';有可能有相同的样式和不同的替换品吗?,php,regex,preg-replace,preg-match,str-replace,Php,Regex,Preg Replace,Preg Match,Str Replace,我创建了这个模式 $pattern = "/<a href='(?<href>.+?)'>(?<name>.+?)<\/a>/i"; 问题是当我使用preg_replace时,因为模式是相同的,所以它更改了所有URL的相同信息,我只需要更改名称并相应地保留其余信息 使用 if(preg_match_all($pattern, $string, $matches)) { $string = preg_replace($pattern, "&

我创建了这个模式

$pattern = "/<a href='(?<href>.+?)'>(?<name>.+?)<\/a>/i";
问题是当我使用preg_replace时,因为模式是相同的,所以它更改了所有URL的相同信息,我只需要更改名称并相应地保留其余信息

使用

if(preg_match_all($pattern, $string, $matches))
{
    $string = preg_replace($pattern, "<a href='$1'>Name</a>", $string);

}
if(preg\u match\u all($pattern,$string,$matches))
{
$string=preg_replace($pattern,“,$string);
}
我可以从组中获得结果,并保留href的第一部分。但是如果我尝试更改名称,所有结果都是一样的

如果我尝试使用“str_replace”,我可以得到预期的不同结果,但这给了我两个问题。一个是,如果我尝试替换名称,我也会更改href,如果我有类似的带有“更多斜杠”的URL,它将更改匹配部分,并保留其余信息

在数据库中,我有一个URL列表,其中有一列有名称,如果字符串与表中的任何行匹配,我需要相应地更改名称并保留href

有什么帮助吗

多谢各位


亲切的问候

我假设您使用如下格式从数据库检索行:

$rows = [
  ['href' => 'https://www.php.net/', 'name' => 'PHP.net'],
  ['href' => 'https://stackoverflow.com/', 'name' => 'Stack Overflow'],
  ['href' => 'https://www.google.com/', 'name' => 'Google']
];
从那里,您可以首先使用循环或以下方式创建href->name映射:

然后,您可以使用将每个匹配项替换为其关联名称(如果存在):

$result = preg_replace_callback($pattern, function ($matches) use ($rows_by_href) {
  return "<a href='" . $matches['href'] . "'>" 
    . ($rows_by_href[$matches['href']] ?? $matches['name']) 
    . "</a>";
}, $string);

echo $result;
$result=preg\u replace\u回调($pattern,function($matches)use($rows\u by\u href){
返回“”;
},$string);
回声$结果;
演示:

请注意,这假设
$string
中的URL(href)的格式与数据库中的URL格式完全相同。否则,您可以
rtrim
后面的斜杠,或者事先执行任何需要的操作


还要注意,如果可以避免的话,用正则表达式解析HTML通常是个坏主意。DOM解析器更合适,除非您必须解析来自评论、论坛帖子或其他不在您控制范围内的内容的字符串。

看起来有点像、、、不知道preg\u replace\u回调。谢谢你的帮助。
$rows = [
  ['href' => 'https://www.php.net/', 'name' => 'PHP.net'],
  ['href' => 'https://stackoverflow.com/', 'name' => 'Stack Overflow'],
  ['href' => 'https://www.google.com/', 'name' => 'Google']
];
$rows_by_href = array_reduce($rows, function ($rows_by_href, $row) {
  $rows_by_href[$row['href']] = $row['name'];
  return $rows_by_href;
}, []);
$result = preg_replace_callback($pattern, function ($matches) use ($rows_by_href) {
  return "<a href='" . $matches['href'] . "'>" 
    . ($rows_by_href[$matches['href']] ?? $matches['name']) 
    . "</a>";
}, $string);

echo $result;