php - 使用关联数组的索引创建可点击的链接

标签 php jquery arrays wordpress hyperlink

我有一个像这样的链接关联数组

$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/

相关文章:

javascript - 如何根据元素id制作动态模态窗口?

javascript - 查找所有 <td> 元素的数字 ID 名称

python - 在 numpy 中创建下一个有效 bool 值的索引数组

php - 创建 "Engine"以允许集成到主 Web 应用程序?

php - Laravel 迁移 Postgres 报错

php - 如何在 MAC/OSX 上从源代码编译 PHP

jquery - L 值是预期的 javascript

c++ - memcpy 如何处理指向数组的指针?

C++ 入门 - 数组的指针和引用

Php MySQL导入csv返回查询,不添加到数据库