在每个字符串周围添加链接值

时间:2013-06-18 02:47:10

标签: php codeigniter hyperlink

我有一个从我的数据库回来的php值作为字符串,比如

"this, that, another, another"

我正试图在每个字符串周围包含一个单独的链接,但我似乎无法让它工作。我尝试了一个for循环,但因为它只是一串信息,而不是一个不起作用的信息数组。有没有办法在我的字符串中的每个值周围包装一个唯一的链接?

3 个答案:

答案 0 :(得分:2)

我认为最简单的方法是使用PHP的explode()函数。当你开始越来越多地使用PHP时,你会发现它会变得非常有用,所以请查看它的documentation page。它允许您在给定某个分隔符的情况下将字符串拆分为数组。在您的情况下,这将是,。所以要拆分字符串:

$string = 'this, that, another, another 2';
$parts = explode(', ', $string);

然后使用foreach(再次检查文档)迭代每个部分并将它们组成链接:

foreach($parts as $part) {
    echo '<a href="#">' . $part . "</a>\n";
}

但是,您可以使用for循环执行此操作。字符串可以像数组一样访问,因此您可以实现解析器模式来解析字符串,提取部分并创建链接。

// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = "";  // final output
$buffer = "";  // buffer to hold current part

// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
    // If the character is our separator
    if($str[$i] === ',') {
        // We've reached the end of this part, so add it to our output
        $output .= '<a href="#">' . trim($buffer) . "</a>\n";
        // clear it so we can start storing the next part
        $buffer = "";
        // and skip to the next character
        continue;
    }

    // Otherwise, add the character to the buffer for the current part
    $buffer .= $str[$i];
}

echo $output;

Codepad Demo

答案 1 :(得分:1)

第一个explode字符串,用于获取数组中的单个单词。然后将超链接添加到单词中,最后添加implode

$string = "this, that, another, another";
$words = explode(",", $string);

$words[0] = <a href="#">$words[0]</a>
$words[1] = <a href="#">$words[1]</a>
..

$string = implode(",", $words);

您还可以使用for循环来指定遵循以下模式的超链接:

for ($i=0; $i<count($words); $i++) {
   //assign URL for each word as its name or index
}

答案 2 :(得分:1)

更好的方法就是这样做

$string = "this, that, another, another";
$ex_string = explode(",",$string);

foreach($ex_string AS $item)
{
   echo "<a href='#'>".$item."</a><br />";
}