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

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

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

必需的输出:使用高于array的索引创建可点击的链接

<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()用锚标记替换链接标题。

PHP PDO组按列名称查询结果 - php

以下PDO查询返回以下结果:$db = new PDO('....'); $sth = $db->prepare('SELECT ...'); 结果如下: name curso ABC stack CDE stack FGH stack IJK stack LMN overflow OPQ overflow RS…

php Singleton类实例将在多个会话中保留吗? - php

举一个简单的例子,如果我想计算一个不使用磁盘存储的脚本的命中次数,我可以使用静态类成员来执行此操作吗?用户1:<?php $test = Example::singleton(); $test->visits++; ?> 用户2:<?php $test = Example::singleton(); $test->visits+…

PHP:对数组排序 - php

请如何排序以下数组Array ( 'ben' => 1.0, 'ken' => 2.0, 'sam' => 1.5 ) 至Array ( 'ken' => 2.0, 'sam' => 1.5, 'ben' =&…

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…