如何根据特定的分隔符将字符串转换为数组?

时间:2015-11-17 13:07:00

标签: php html explode implode

我有一个这样的字符串:

$str = "it, is, a, test";

现在,我想要这个:(分隔符是,

<small>
 <a href='#'>it</a>
 <a href='#'>is</a>
 <a href='#'>a</a>
 <a href='#'>test</a>
</small>

我该怎么做?

6 个答案:

答案 0 :(得分:4)

echo "<small><br/>";
$str = "it, is, a, test";
$arr = explode(', ',$str);
foreach ($arr as $data)
    echo "<a href='#'>" . $data . "</a><br/>";
echo "</small>";

答案 1 :(得分:3)

只需使用explode ..

$str = "it, is, a, test";

$res = explode( ', ', $str );

echo "<small>";
foreach($res as $result){
    echo "<a href='#'>" . $result . "</a>";

    }
echo "</small>";

https://ideone.com/XvIF67

答案 2 :(得分:2)

您可以使用explode之类的

echo "<small>";
$wordArray = explode(', ',$str);
foreach($wordArray as $word) {
    echo "<a href='#'>".$word."</a>";
}
echo "</small>";

答案 3 :(得分:2)

echo "<pre><br/>";
$str = "it, is, a, test";
$arr = explode(', ',$str);
echo "<small>";
foreach($arr as $item){
echo <a href='#'>$item</a>
}
echo "</small>";

答案 4 :(得分:1)

您正在寻找的功能是explode

$str = "it, is, a, test";
$arr = explode(', ', $str);
echo "<small>\n";
foreach ($arr as $word) {
    echo "  <a href='#'>$word</a>\n";
}
echo "</small>\n";

答案 5 :(得分:0)

试试这个:

# Between 1 and 100, there are exactly 5 numbers with exactly 12 factors. What are they?
x = 1
list_of_five = []
list_of_factors = []
while x < 101:
    y = 1
    list_of_factors = []
    while y < (x+1):
        if (x/y) == int(x/y) and not((x/y) in list_of_factors):
            list_of_factors.append((x/y))
            if len(list_of_factors) == 12:
                list_of_five.append(x)
                print(str(x) + ":")
                print(list_of_factors)
        y+=1
    x+=1
print("The list of numbers is:" + str(list_of_five)) #This should be the solution to the problem.

如您所见,在第一个echo "<small><a href='#'>".implode("</a><a href='#'>", explode(', ',$str))."</a></small>"; 函数中分隔字符串并创建一个关键字数组,然后explode()函数将它们组合在一起并创建您需要的内容。

<强>输出:

impode()

这是demo