我正试图为我面临的问题找到解决方案。我有以下段落
Lorem ipsum dolor坐下,!qwerty 奉献自若。 Quisque sapien velit,aliquet eget commodo nec,auctor a sapien。 !qwerty Nam eu neque vulputate diam rhoncus ! bart faucibus。 Curabitur quis varius libero。洛雷姆。
我必须消除以!开头的重复值。例如:在段落中有两个!qwerty字符串,我想通知插入该段落的用户将重复值限制为一个而不会影响第三个!bart标记,我该如何在php中做到这一点。到目前为止,我尝试了strcmp,preg_match和str_pos,但都没有用,这让我头疼。
到目前为止我尝试过的代码(如果有不必要的代码,因为我还在学习,很抱歉):
$data="Lorem ipsum dolor sit amet, !qwerty consectetur adipiscing elit. Quisque sapien velit, aliquet eget commodo nec, auctor a sapien. !qwerty Nam eu neque vulputate diam rhoncus !bart faucibus. Curabitur quis varius libero. Lorem.";
$dat= explode(" ", $data);//names are exploded in to array
foreach($dat as $d) {
$compare1=in_array($d,$dat);
if(strpos($d ,'!') !== FALSE ){
$i=0;
$d2=count($dat);
while ($i<$d2) {
$d_w=$dat[$i];
//print_r($d_w);
$regex="/!+([a-zA-z0-9._-]+)/";
$d1= preg_match($regex, $d);
$i++;
$d21=$d;
$d3= count($d2);
$d4= parse_str($d2,$out);
$d5===strcmp($d, $d_w);
$d6=== strpos($d_w, $d);
var_dump("<p>".$d5."</p><i>".$d6);
if ($d21===$d_w ) {
$tag=1;
$d7=$tag+tag;
print_r("<span>".$tag."</span>");echo '<br>';print_r("<p>".$d7);
if($d7>1){
echo 'only one tag is allowed per post';
}
}
}
//var_dump($compare1);
exit();
}
答案 0 :(得分:0)
尝试以下解决方案:
$data1="Lorem ipsum dolor sit amet, !qwerty consectetur adipiscing elit. Quisque sapien velit, aliquet eget commodo nec, auctor a sapien. !qwerty Nam eu neque vulputate diam rhoncus !bart faucibus. Curabitur quis varius libero. Lorem.";
function findIfDataHaveRepeatPattern ($data) {
// First, use regex to grab all pattern at once.
if (preg_match_all('/!\w+/u', $data, $matches)) {
foreach ($matches[0] as $crrTargetStr) {
$targetStrCollection[] = $crrTargetStr;
}
}
sort($targetStrCollection);
// Second, sort() the array element. After sorting will makes finding duplication
// much more easier because now we only need to check/compare
// if every nearby element are the same or not.
$countOfCollection = count($targetStrCollection);
if ($countOfCollection > 1) {
for ($i = 0 ; $i < count($targetStrCollection) ; $i++) {
if ($i === $countOfCollection - 1) {
return FALSE;
}
if ($targetStrCollection[$i] === $targetStrCollection[$i + 1]) {
// If nearby element are the same, it means this SORTED array has duplicated pattern.
return $targetStrCollection[$i];
}
}
} else {
return FALSE;
}
}
function printIfDataHaveRepeatPattern ($data) {
$testResult = findIfDataHaveRepeatPattern($data);
// If return value is FALSE, then nothing duplicated
// , if return value is a string, then it is the duplicated string.
if ($testResult) {
echo("Duplicate on pattern " . $testResult . " in your input.");
} else {
echo("No duplicate pattern in your input.");
}
}
printIfDataHaveRepeatPattern($data1);
// Will show "Duplicate on pattern !qwerty in your input.".
这可以解决您的问题吗?询问更多是否需要更多帮助。