3 回答

TA貢獻1820條經驗 獲得超9個贊
此代碼訴諸檢查每一行以查看它是否與您的$unwanted字符串匹配,但它還會創建一個它已經遇到過的字符串數組,以便檢查之前是否遇到過( using in_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 );

TA貢獻1801條經驗 獲得超16個贊
<?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

TA貢獻1836條經驗 獲得超4個贊
這是您可以執行此操作的一種方法:
$string = 'this
this
good
good
hahah';
preg_match_all('/([a-z])+/', $string, $matches);
$string = implode("\n",array_unique($matches[0]));
echo $string;
- 3 回答
- 0 關注
- 135 瀏覽
添加回答
舉報