【发布时间】:2019-09-03 23:56:30
【问题描述】:
我创建了这个模式
$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。
有什么帮助吗?
谢谢。
亲切的问候!
【问题讨论】:
标签: php regex preg-replace preg-match str-replace