<?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();
?>
I want to remove duplicate [video=1] in $stripper, this is the result i need:
我想在$ stripper中删除重复的[video = 1],这是我需要的结果:
Content...1_195, content...content...2_963,
content...content...content..., no more...
I am using array_unique() function to remove the duplicate array. From my code above, if i print_r($unique), the duplicate array has been removed:
我正在使用array_unique()函数来删除重复的数组。从上面的代码,如果我print_r($ unique),重复的数组已被删除:
Array ( [0] => [video=1] [1] => [video=2] )
But if i echo get_video(), the duplicate [video=1] still exist:
但如果我回显get_video(),副本[video = 1]仍然存在:
Content...1_195, content...content...2_963,
content...content...content...1_195([video=1]), no more...
I can't figure out why!!! :(
我无法弄清楚为什么! :(
Demo: http://eval.in/7178
演示:http://eval.in/7178
2 个解决方案
#1
2
To remove duplicates execute a preg_replace_callback
and replace the duplicate one by "". Use the following code just before your preg_match_all
call,
要删除重复项,请执行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
#2
1
You can try this;
你可以试试这个;
$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);
Outputs;
输出;
Array
(
[1] => 1
[2] => 2
)
#1
2
To remove duplicates execute a preg_replace_callback
and replace the duplicate one by "". Use the following code just before your preg_match_all
call,
要删除重复项,请执行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
#2
1
You can try this;
你可以试试这个;
$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);
Outputs;
输出;
Array
(
[1] => 1
[2] => 2
)