我在下面有一个示例字符串,并希望删除任何单个字符,因此以下内容:
$string = 'N W N W Some useful test what I would like to keep'
可以成为:$stringNew = 'Some useful test what I would like to keep'
此外,我想要一个通用的解决方案,因为上面的字符串会有所不同,字符串中的独立字母也会有所不同。 非常感谢任何帮助。
答案 0 :(得分:3)
使用preg_replace()
执行此操作。使用以下代码
<?php
$string = 'N W N W Some useful test what I would like to keep'
echo preg_replace('/\b\w\b\s?/', '', $string); // will print Some useful test what would like to keep
?>
如果您不想让我被替换,请使用此代码
<?php
$string = "N W N W Some useful test what I would like to keep";
$array = explode(" ",$string);
$new = "";
foreach($array as $p){
if($p=="I"){
echo " ".$p;
}
else{
if(strlen($p)!==1){
echo " ".$p;
}
}
}
echo trim($new); // will print Some useful test what I would like to keep
?>
希望这有助于你