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

How to convert a string to an array according to a specific separator?

我有这样的字符串:

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

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

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

我该怎么做?

你可以explode喜欢

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

您要查找的函数是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";

只需使用 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

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

试试这个:

echo "<small><a href='#'>".implode("</a><a href='#'>", explode(', ',$str))."</a></small>";

如您所见,首先 explode() 函数分离字符串并创建关键字数组,然后 impode() 函数组合它们并创建您需要的内容。

输出:

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

这里是demo.