2013-01-21 29 views
0
<?php 

function get_video() { 

$stripper = "Content...[video=1], content...content...[video=2], 
      content...content...content...[video=1], no more..."; 

preg_match_all("/\[video=(.+?)\]/smi", $stripper, $search); 

$unique = array_unique($search[0]); 

$total = count($unique);  
for($i=0; $i < $total; $i++) 
{  
    $vid = $search[1][$i]; 
    if ($vid > 0) 
    {  
    $random_numbers = rand(1, 1000); 
    $video_id = $vid."_".$random_numbers; 
    $stripper = str_replace($search[0][$i], $video_id, $stripper); 
    } 
} 
return $stripper; 
} 

echo get_video(); 
?> 

我想删除重复的[视频= 1] $脱衣舞,这是结果,我需要:正则表达式卸下串重复比赛

Content...1_195, content...content...2_963, 
content...content...content..., no more... 

我使用array_unique()函数删除重复的数组。从上面我的代码,如果我的print_r($唯一的),重复的阵列已被移除:

Array ([0] => [video=1] [1] => [video=2]) 

但是,如果我回声get_video(),重复的[视频= 1]仍然存在:

Content...1_195, content...content...2_963, 
content...content...content...1_195([video=1]), no more... 

我不明白为什么! :(

演示:http://eval.in/7178

回答

2

删除重复执行preg_replace_callback和替换用 “” 重复一个只是你preg_match_all调用之前使用下面的代码,

$hash = array(); 
$stripper = preg_replace_callback("/\[video=(.+?)\]/smi",function($m){ 
    global $hash; 
    if(isset($hash[$m[0]])) 
     return ""; 
    else{ 
     $hash[$m[0]]=1; 
     return $m[0]; 
    } 
}, $stripper); 

http://eval.in/7185

+0

完美!谢谢! – richard

1

您可以试试这个;

$stripper = "Content...[video=1], content...content...[video=2], 
       content...content...content...[video=1], no more..."; 
preg_match_all("/\[video=([^\]]*)/i", $stripper, $matches); 
$result = array(); 
foreach ($matches[1] as $k => $v) { 
    if (!isset($result[$v])) { 
     $result[$v] = $v; 
    } 
} 
print_r($result); 

输出;

Array 
(
    [1] => 1 
    [2] => 2 
)