Best Way To Concatenate Strings In PHP With Spaces In Between

蹲街弑〆低调 提交于 2019-12-21 07:46:17

问题


I need to concatenate an indeterminate number of strings, and I would like a space in between two adjoining strings. Like so a b c d e f.

Also I do not want any leading or trailing spaces, what is the best way to do this in PHP?


回答1:


You mean $str = implode(' ', array('a', 'b', 'c', 'd', 'e', 'f'));?




回答2:


$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"



回答3:


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");



回答4:


Simple way is:

$string="hello" . " " . "world";



回答5:


considering that you have all these strings collected into an array, a way to do it could be trough a foreach sentence like:

$res = "";
foreach($strings as $str) {
   $res.= $str." ";
}

if(strlen($res > 0))
    $res = substr($res,-1);

in this way you can have control over the process for future changes.




回答6:


I just want to add to deviousdodo's answer that if there is a case that there are empty strings in the array and you don't want these to appear in the concatenated string, such as "a,b,,d,,f" then it will better to use the following:

$str = implode(',', array_filter(array('a', 'b', '', 'd', '', 'f')));



来源:https://stackoverflow.com/questions/8068428/best-way-to-concatenate-strings-in-php-with-spaces-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!