在 PHP 中用空格连接字符串的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8068428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:53:38  来源:igfitidea点击:

Best Way To Concatenate Strings In PHP With Spaces In Between

phpstringconcatenation

提问by freshest

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.

我需要连接不确定数量的字符串,并且我希望在两个相邻的字符串之间有一个空格。像这样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?

另外我不想要任何前导或尾随空格,在 PHP 中执行此操作的最佳方法是什么?

回答by deviousdodo

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

你的意思是$str = implode(' ', array('a', 'b', 'c', 'd', 'e', 'f'));

回答by Esailija

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

回答by Dejan Marjanovic

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

回答by user2033108

Simple way is:

简单的方法是:

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

回答by holographix

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

考虑到您已将所有这些字符串收集到一个数组中,一种方法可能是通过 foreach 句子,例如:

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

通过这种方式,您可以控制未来更改的流程。

回答by gnl

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:

我只想在 deviousdodo 的回答中补充一点,如果数组中有空字符串并且您不希望它们出现在连接的字符串中,例如 "a,b,,d,,f" 那么最好使用以下内容:

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

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