通过将字符串应用为 的 href 和文本,将一维字符串数组转换为锚超链接。标签
我想用类似的东西包装数组的所有元素,但我不想要很多行或 foreach 循环
$links = array('london','new york','paris');
结果应该是
<a href="#london">london</a>
<a href="#new york">new york</a>
<a href="#paris">paris</a>
I would like to wrap all elements of an array with something like but I don't want a lot of lines or foreach loop
$links = array('london','new york','paris');
The outcome should be
<a href="#london">london</a>
<a href="#new york">new york</a>
<a href="#paris">paris</a>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
array_map 怎么样?
演示(点击源码)
没有 PHP > 5.3,你不能使用 lambda 函数,所以你需要这样的东西:
PHP 5.2 演示< /a> (再次单击“源”)
How about array_map?
Demo (Click source)
Without PHP > 5.3, you can't use a lambda function, so you'll need something like this:
Demo for PHP 5.2 (Again, click Source)
尝试 join('\n', array_map(function($a) { return "$a<\\a>";}, $links) );
Try
join('\n', array_map(function($a) { return "<a href=\"#$a\",>$a<\\a>";}, $links));
在现代 PHP 版本中,它可以缩短如下。
On modern PHP versions it could be shorten as follows.
可重复使用的功能。
Reusable function.
另一种尚未提及的技术是使用 preg_replace() ,它将愉快地迭代字符串数组,尽管显然这并不是一个真正需要正则表达式模式的任务。 (演示)
否则,您可以通过调用
urlencode()< 来执行额外的步骤来生成编码的 URL /code> 位于用作
href
值的城市字符串上。Another technique not yet mentioned is to use
preg_replace()
-- which will happily iterate an array of strings -- although, obviously this is not a task that actually demands a regex pattern. (Demo)Otherwise, you can go that extra step toward generating encoded urls by calling
urlencode()
on the city string which is used as thehref
value.