在每个类别后添加逗号

时间:2016-06-10 22:09:21

标签: php

这似乎是一个非常直截了当的问题,由于某种原因,我无法弄清楚如何实现我正在寻找的东西。

$category = $html2->find('.video_cats',0);
$category = $genre->plaintext;


<div class="video_cats">
<span>Categories:</span>
    <a href="http://www.example.com" title="Example Category" class="video_cat">House</a>   
    <a href="http://www.example.com" title="Example Category" class="video_cat">The Cat</a> 
    <a href="http://www.example.com" title="Example Category" class="video_cat">Car</a> 
    <a href="http://www.example.com" title="Example Category" class="video_cat">The Dog</a>                                                             
</div>

目前我有一个名为$category的字符串,如果我们print此字符串的结果将返回以下文字 One Two Three Four Five 我试图让它返回文本 一,二,三,四,五 。非常感谢任何帮助。

编辑: 这是所需的输出 类别:猫,狗,马,众议院 因为某些类别名称中有空格我们不能用逗号替换空格。

2 个答案:

答案 0 :(得分:1)

搜索锚点而不是DIV,然后你可以遍历它们并创建一个数组。

$cat_array = array():
foreach ($html2->find(".video_cat") as $cat) {
    $cat_array[] = $cat->plaintext;
}

$category = implode(', ', $cat_array);

答案 1 :(得分:0)

您可以像这样使用explodeimplode

$category = implode(", ", explode(" ", $category));

然后打印出$category的新内容。

考虑到您的编辑后,上述操作无法正常工作,但是如果您使用split代替explode,则可以使用正则表达式在预先列表中执行反向引用匹配 - 定义的单词,例如:&#34; A&#34;,&#34;&#34;等...(参见:http://www.regular-expressions.info/refcapture.html

这可能是一个解决方案,但仍然存在问题。最好的方法是找到一种更好地划分列表的方法。