我需要将数量不确定的字符串连接起来,并且希望两个相邻字符串之间有一个空格。例如:a b c d e f
。
同时,我不想要任何前导或后续空格,请问PHP中最好的方法是什么?
我需要将数量不确定的字符串连接起来,并且希望两个相邻字符串之间有一个空格。例如:a b c d e f
。
同时,我不想要任何前导或后续空格,请问PHP中最好的方法是什么?
$str = implode(' ', array('a', 'b', 'c', 'd', 'e', 'f'));
吗?简单的方法是:
$string="hello" . " " . "world";
$strings = array( " asd " , NULL, "", " dasd ", "Dasd ", "", "", NULL );
function isValid($v){
return empty($v) || !$v ? false : true;
}
$concatenated = trim( implode( " ", array_map( "trim", array_filter( $strings, "isValid" ) ) ) );
//"asd dasd Dasd"
function concatenate()
{
$return = array();
$numargs = func_num_args();
$arg_list = func_get_args();
for($i = 0; $i < $numargs; $i++)
{
if(empty($arg_list[$i])) continue;
$return[] = trim($arg_list[$i]);
}
return implode(' ', $return);
}
echo concatenate("Mark ", " as ", " correct");
我想要补充一下deviousdodo的回答。如果数组中包含空字符串,并且你不希望它们出现在连接的字符串中,例如 "a,b,,d,,f",那么最好使用以下方式:
$str = implode(',', array_filter(array('a', 'b', '', 'd', '', 'f')));
$res = "";
foreach($strings as $str) {
$res.= $str." ";
}
if(strlen($res > 0))
$res = substr($res,-1);
通过这种方式,您可以控制未来更改的过程。
implode()
函数时,这听起来过于复杂了。 - kapaforeach
)假设字符串在一个数组中。使用 implode
也会假设字符串在一个数组中。我看不到这里的自由,只看到一堆不必要的代码行,降低了可读性。 - kapa