猿问

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

我想保留一个...请帮帮我,谢谢你们


一只名叫tom的猫
浏览 92回答 4
4回答

胡子哥哥

此代码用于检查每行以查看它是否与您的字符串匹配,但它也会创建一个已遇到的字符串数组,以便检查以前是否遇到过(使用)。如果它匹配并且已经遇到之前,它在原始使用中删除该行...$unwantedin_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 );

阿晨1998

<?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

四季花海

以下是您可以执行此操作的一种方法:$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;

回首忆惘然

您可以使用php内置函数array_unique<?php&nbsp; &nbsp;$string = 'thisthisgoodgoodhaha';&nbsp; &nbsp; $rows = explode("\n",$string);&nbsp; &nbsp; $cleanArray = array_unique($rows);&nbsp; &nbsp; $cleanString=implode("\n",$cleanArray);print_r ( $cleanString );//result is this good haha
随时随地看视频慕课网APP
我要回答