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 );
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
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;
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
- 4 回答
- 0 关注
- 90 浏览
添加回答
举报