10

我要拆分的字符串$item['category_names']例如包含Hair, Fashion, News

我目前有以下代码:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
    $categories = "<category>" . $cat . "</category>\n";
}

我希望结果$categories如下所示,以便稍后在某处回显。

<category>Hair</category>\n
<category>Fashion</category>\n
<category>News</category>\n

不确定我是否走对了这条路?

4

5 回答 5

28

在您的代码中,您将在每次迭代中覆盖 $categories 变量。正确的代码如下所示:

$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
    $cat = trim($cat);
    $categories .= "<category>" . $cat . "</category>\n";
}

更新:正如@Nanne 建议的那样,仅在“,”上爆炸

于 2012-05-18T10:33:31.580 回答
2

没有 for 循环

$item['category_names'] = "Hair,   Fashion,   News";
$categories = "<category>".
        implode("</category>\n<category>", 
        array_map('trim', explode(",", $item['category_names']))) . 
        "</category>\n";
echo $categories;
于 2012-05-18T10:42:35.583 回答
1

如果你使用这个:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}

$categories 字符串每次都会被覆盖,所以 "hair" 和 "fasion" 都丢失了。

但是,如果您在 for 循环中的等号之前添加一个点,如下所示:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories .= "<category>" . $cat . "</category>\n";
}

$catergories 字符串将包含所有三个值:)

于 2012-05-18T10:35:16.293 回答
1

PHP 循环分解数组 演示:http ://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2

它对我有用

<?php

$str = "name:john,hone:12345,ebsite:www.23.com";

$array=explode(",",$str);

if(count($array)!=0)
{
foreach($array as $value)
{

    $data=explode(":",$value);

      echo $data[0]."=".$data[1];


    echo ' ';

}
}
?>
于 2018-09-15T07:18:28.583 回答
0

您的代码中的错误是这样的:

$categories = "<category>" . $cat . "</category>\n";

您在每次迭代时都覆盖$categories,它应该是:

$categories .= "<category>" . $cat . "</category>\n";

不确定我是否走对了这条路?

查找和替换不是爆炸的目的。如果您只想更正代码错误 - 请参见上文。

这更有效:

$categories = "<category>" .
    str_replace(', ', "</category>\n<category>", $input) . 
    "</category>\n";

这也解释了可变空格:

$categories = "<category>" . 
    preg_replace('@\s*,\s*@', "</category>\n<category>", $input) . 
    "</category>\n";
于 2012-05-18T10:42:04.520 回答