我有一个像这样的链接关联数组
$my_links = [
'city 1' => 'http://link1',
'city 2' => 'http://link2',
'Head Office' => 'http://link3'
];
和一些像这样的html。 html由脚本动态生成(wordpress博客内容)。
<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>
所需输出:使用上述数组
的索引创建可点击的链接
<p>
You can visit our stores at <a href="http://link1">City 1</a>
and <a href="http://link2">City 2</a>,
or visit our <a href="http://link3">Head office</a>.
</p>
如何使用 PHP
和/或 JQuery
实现此目的?
最佳答案
<?php
$my_links = [
'city 1' => 'http://link1',
'city 2' => 'http://link2',
'Head Office' => 'http://link3'
];
$str = "<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>";
foreach ($my_links as $link_title => $link) {
$str = str_ireplace($link_title,"<a href='$link'>".ucwords($link_title)."</a>",$str);
}
echo $str;
循环您的$my_links
。找到字符串中存在的链接标题并使用 str_ireplace()用 anchor 标记替换链接标题。
关于php - 使用关联数组的索引创建可点击的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417615/