2013-05-22 36 views
-4

我试图在Google和Google上找到答案,但没有运气!爆炸不适用字符串内的多重逗号

为什么当我尝试爆炸弦时它不起作用?

$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 

$Text_Array = explode(",",$Text); 

$Text_Array = array_filter($Text_Array); 

print_r($Text_Array); 

我想我所有的标签除以一个逗号,并删除任何空间和重复标签。

我想这样的结果:

“巴西,银行,家居,英国,测试,金融时报,iPad的,两个字”;

请问,你能帮我实现吗?

+2

在爆炸之前使用str_replace();或者使用str_getcsv() –

+6

定义“不起作用”。会发生什么,你期望什么呢? – deceze

+0

预期的结果是什么? – Robert

回答

3

如果你想remove any space and duplicate tags,那么你还需要与array_filter

$textAray = array_unique(array_filter($textAray)); 

注意添加array_unique ..请这不会在结果中去除. ..这里更好的方式来筛选结果

$text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 
$textArray = array_unique(preg_split("/[,.]+/", $text)); 
$textArray = array_filter($textArray); 
echo implode(",", $textArray); 

输出

brazil,banks,home,uk,test,financial times,ipad,Two words 
+1

是的,这是我的问题的最佳答案。最好的解决方案!谢谢。 –

+0

不客气.... – Baba

0

你需要的是array_unique功能:

$Text_Array = array_unique($Text_Array); 

所以,你的代码就变成了:

$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 

$Text_Array = explode(",",$Text); 

$Text_Array = array_filter($Text_Array); 

$Text_Array = array_unique($Text_Array);\ 

print_r($Text_Array); 

,然后你会得到所需的输出。

0

您爆炸前的字符串

$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 

$Text = preg_replace("/,+/", ",", $Text); 
$Text_Array = explode(",",$Text); 

print_r($Text_Array); 

注意,你仍然有一个元素的数组中包含一个点,该数组的最后一个元素将是您可以通过一个单一的逗号替代多个连续逗号如果您的字符串以逗号结尾,则为空。

0

你需要这样那样的代码

$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 

$str = substr(preg_replace('/(.+?)[,]+/', '$1,', $Text),0,strlen($str)-1); 
$arr = array_unique(explode(',', $str)); 
print_r($arr); 
  1. 您需要使用一个替换,,或更多,我已经做了preg_replace它
  2. 删除最后,从字符串
  3. 爆炸by,
  4. 删除array_unique()的重复项
0

u ma Ÿ试试这个

<?php 

$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 

$Text=str_replace(array(",,",",,,,",",.,",",,"),',',$Text); 

$Text_Array = explode(",",$Text); 

$Text_Array = array_filter($Text_Array); 

print_r($Text_Array); 
//output :: Array ([0] => brazil [1] => banks [2] => home [3] => uk [4] => test [5] => financial times [6] => ipad [7] => banks [8] => Two words) 
?> 
0

试试这个:

<?php 
$Text = "brazil,banks,home,,uk,,,,test,financial times,.,ipad,,banks,,Two words,,"; 
$Text = str_replace('.','',implode(',',array_unique(explode(',', $Text)))); 
$Text_Array = explode(",",$Text); 

$Text_Array = array_filter($Text_Array); 

print_r($Text_Array); 
?> 
0

您可以通过替换 ',,' 删除所有unncessary commata在你的榜样 '' 直到没有更多的 ',,' 存在。

while (strstr($Text,',,') !== false) { 
    $Text = str_replace($Text,',,',','); 
} 

使用的功能:

0

除了这些人给出的解决方案,你可以试试这个为u想打印值: -

foreach($Text_Array as $textval) 
{ 
echo $textval . ","; 
}