亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

php 刪除重復項,但原始內容除外

php 刪除重復項,但原始內容除外

PHP
一只名叫tom的貓 2022-08-05 10:00:31
這是我的代碼   <?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我想保留一個...請幫幫我,謝謝你們
查看完整描述

4 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

此代碼用于檢查每行以查看它是否與您的字符串匹配,但它也會創建一個已遇到的字符串數組,以便檢查以前是否遇到過(使用)。如果它匹配并且已經遇到之前,它在原始使用中刪除該行...$unwantedin_array()unset()$rows


$string = 'this

    this

    good

   good

    hahah';


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

$unwanted = 'this|good';

$matched = [];

foreach ( $rows as $line => $row )   {

    if ( preg_match("/$unwanted/i",$row, $matches))  {

        if ( in_array(trim($matches[0]), $matched) === true )    {

            unset($rows[$line]);

        }

        $matched[] = $matches[0];

    }

}

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

print_r ( $cleanString );


查看完整回答
反對 回復 2022-08-05
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

<?php

    $string = 'this

    this 

    good

    yyyy

    good

    xxxx

    hahah';


    print_r(

       implode("\n", 

          array_diff(array_unique(

             array_map(function($v) { return trim($v);}, explode("\n",$string))

          )

       ,array('xxxx', 'yyyy')))

    );


?>

輸出:


this

good

hahah

參考: https://ideone.com/Eo0MIM


查看完整回答
反對 回復 2022-08-05
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

以下是您可以執行此操作的一種方法:


$string = 'this

    this 

    good 

    good 

    hahah';


preg_match_all('/([a-z])+/', $string, $matches);

$string = implode("\n",array_unique($matches[0]));

echo $string;


查看完整回答
反對 回復 2022-08-05
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

您可以使用php內置函數array_unique


<?php

   $string = 'this

this

good

good

haha';


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

    $cleanArray = array_unique($rows);

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

print_r ( $cleanString );


//result is this good haha


查看完整回答
反對 回復 2022-08-05
  • 4 回答
  • 0 關注
  • 118 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號