这个问题在这里已有答案:
我创造了这种模式
$pattern = "/<a href='(?<href>.+?)'>(?<name>.+?)<\/a>/i";
我有这个例子,
$string = "<a href='https://www.php.net/'>https://www.php.net/</a>
<a href='https://stackoverflow.com/'>https://stackoverflow.com/</a>
<a href='https://www.google.com/'>https://www.google.com/</a>";
使用这个,我可以找到匹配并提取href和名称。
preg_match_all($pattern, $string, $matches);
Array
(
[0] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[href] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[1] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[name] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
[2] => Array
(
[0] => https://www.php.net/
[1] => https://stackoverflow.com/
[2] => https://www.google.com/
)
)
问题是当我使用preg_replace时,由于模式相同,它会更改所有URL的相同信息,我只需要更改名称并相应地保留其余信息。
使用,
if(preg_match_all($pattern, $string, $matches))
{
$string = preg_replace($pattern, "<a href='$1'>Name</a>", $string);
}
我可以从组中获得结果,并保留href的第一部分。但是,如果我尝试更改名称,则所有结果都是相同的。
如果我尝试使用“str_replace”,我可以按预期得到不同的结果,但这给了我2个问题。一个是如果我尝试替换名称,我也会更改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']
];
从那里,您可以首先使用循环或array_reduce
创建一个href - >名称映射:
$rows_by_href = array_reduce($rows, function ($rows_by_href, $row) {
$rows_by_href[$row['href']] = $row['name'];
return $rows_by_href;
}, []);
然后,您可以使用preg_replace_callback
将每个匹配项替换为其相关名称(如果存在):
$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;
但是:ぁzxswい
请注意,这假设https://3v4l.org/IY6p0中的URL(href)的格式与来自数据库的URL完全相同。否则你可以$string
拖尾斜线或事先做你需要的任何事情。
另请注意,如果可以避免使用正则表达式解析HTML通常是个坏主意。 DOM解析器更合适,除非您必须解析来自评论或论坛帖子的字符串或不在您控件中的字符串。