使用PHP中的正则表达式替换多个href值

时间:2016-11-04 16:45:05

标签: php arrays regex wordpress foreach

我知道这个问题有更多的WordPress背景,但我希望这只是我缺乏PHP知识这里的问题。

我有一个正则表达式,用于查找<a>标记,例如:<a href="http://website.co.uk/post/post-title">Find Out More</a>,这些标记是根据用户输入的内容生成的。找到此内容后,foreach循环会在匹配的文本上运行,并使用WordPress函数$postId = url_to_postid( $url );将URL转换为PostID。

这是一个示例输出:<a href="#171">Find Out More</a>

只要每个匹配文本中有一个链接,这样就可以正常工作。但是,如果有两个或更多链接,则会将每个链接设置为具有相同的href,这是不正确的。

我确定这与我的循环运行方式有关。我使用的代码如下:

<?php
$string = get_field('sample_text_box');
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
preg_match_all($pattern, $string, $matches);
$urls = $matches[0];

foreach($urls as $key => $url) {
$postId[$key] = url_to_postid( $url );
}

$newstring = preg_replace($pattern , $postId[$key] , $string);
echo $newstring;
?>

get_field('sample_text_box');是高级自定义字段功能,&#34; 返回指定字段的值&#34;。如果它有帮助,你可以在这里阅读:https://www.advancedcustomfields.com/resources/get_field/

谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是您确实使用单个值this.props.router替换了该模式,其中$postId[$key]$key中分配的最后一个值。

您也无法传递foreach,因为$postId期望模式和替换都属于同一类型 - 无论是字符串还是数组。

但是,preg_replace函数可以轻松解决问题:

preg_replace_callback