猿问

php删除除原件外的重复项

这是我的代码


   <?php 


    $string = 'this

    this 

    good 

    good 

    hahah';


    $rows = explode("\n",$string);

    $unwanted = 'this|good';

    $cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);

    $cleanString=implode("\n",$cleanArray);

    print_r ( $cleanString );


?>

展示


hahah

我想要这样


this 

good 

hahah

我想保留一个...请帮助我,谢谢大家


神不在的星期二
浏览 101回答 3
3回答

慕妹3146593

此代码诉诸检查每一行以查看它是否与您的$unwanted字符串匹配,但它还会创建一个它已经遇到过的字符串数组,以便检查之前是否遇到过( using in_array())。unset()如果它匹配并且在它用于原始$rows删除该行之前已经遇到......$string = 'this&nbsp; &nbsp; this&nbsp; &nbsp; good&nbsp; &nbsp;good&nbsp; &nbsp; hahah';$rows = explode("\n",$string);$unwanted = 'this|good';$matched = [];foreach ( $rows as $line => $row )&nbsp; &nbsp;{&nbsp; &nbsp; if ( preg_match("/$unwanted/i",$row, $matches))&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ( in_array(trim($matches[0]), $matched) === true )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unset($rows[$line]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $matched[] = $matches[0];&nbsp; &nbsp; }}$cleanString=implode("\n",$rows);print_r ( $cleanString );

侃侃尔雅

<?php&nbsp; &nbsp; $string = 'this&nbsp; &nbsp; this&nbsp;&nbsp; &nbsp; good&nbsp; &nbsp; yyyy&nbsp; &nbsp; good&nbsp; &nbsp; xxxx&nbsp; &nbsp; hahah';&nbsp; &nbsp; print_r(&nbsp; &nbsp; &nbsp; &nbsp;implode("\n",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_diff(array_unique(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;array_map(function($v) { return trim($v);}, explode("\n",$string))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp;,array('xxxx', 'yyyy')))&nbsp; &nbsp; );?>输出:thisgoodhahah参考:https ://ideone.com/Eo0MIM

HUH函数

这是您可以执行此操作的一种方法:$string = 'this&nbsp; &nbsp; this&nbsp;&nbsp; &nbsp; good&nbsp;&nbsp; &nbsp; good&nbsp;&nbsp; &nbsp; hahah';preg_match_all('/([a-z])+/', $string, $matches);$string = implode("\n",array_unique($matches[0]));echo $string;
随时随地看视频慕课网APP
我要回答