php内爆问题

时间:2011-02-24 22:52:33

标签: php

我有一个数组$ x = array(a,b,c);数组的每个元素都是一个URL。

有一个函数链接($ x [$ i]),它将数组的每个元素转换为超链接。

function convert($x){
 $new = explode(',',$x);
 for($i=0;$i<count($new);$i++){
   echo  link($new[$i]);  // converts the url to hyperlink
 }

这会将输出显示为url1 url2等。但是,如果我想要2个网址之间的逗号','。如果没有逗号','如何成为超链接的一部分?

期望的输出将是

hyperlink1 , hyperlink2 etc  // note comma ',' should not be part of the hyperlink

7 个答案:

答案 0 :(得分:3)

您可以使用array_map和implode函数来简化这一过程。

$urls = array('http://www.google.com/', 'http://www.stackoverflow.com/');

$links = array_map("link", $urls);
echo implode(', ', $links);

答案 1 :(得分:1)

$x = array(
  'http://google.pl',
  'http://yahoo.com',
  'http://msn.com'
);

function convert($array){
    $res = array();
    foreach ( $array as $url ) {
        $res[] = '<a href="' . $url . '">' . $url . '</a>';
    }
    return implode(', ', $res);
}

echo convert($x);

答案 2 :(得分:1)

function convert($x){
 for($i=0;$i<count($new);$i++){
   echo  link($new[$i]) . ($i<count($new)-1?", ":"");  // converts the url to hyperlink
 }

答案 3 :(得分:1)

function convert($x){
    return implode(',', array_map('link', explode(',',$x)));
}

答案 4 :(得分:0)

function convert($x)
{
 $string = '';

 foreach($x as $element)
 {
   $string .= link($element).',';
 }

 $string = rtrim($string, ',');

 echo $string;
}

这可以避免最后一个链接在结尾处有逗号,如你所愿。 //回应link1,link2,link3

答案 5 :(得分:0)

$x = array('foo', 'bar', 'baz');

// then either:
$x = array_map('link', $x);

// or:
foreach ($x as &$value) {
    $value = link($value);
}

echo join(', ', $x);

答案 6 :(得分:0)

$output = '';
foreach (explode(',',$x) as $url)
  $output .= link($url);
$output = substr($output,0,-1);
echo $output;