Best way to combine strings in PHP with gaps between them

I need to concatenate an indefinite number of lines, and I need space between two adjacent lines. Thus abcdef .

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

+7
source share
6 answers

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

+26
source
 $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
source
 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"); 
+3
source

A simple way:

 $string="hello" . " " . "world"; 
+2
source

I just want to add to deviousdodo the answer that if there is a case that there are empty strings in the array and you do not want them to appear in the concatenated string, for example, "a, b, d, f", then it is better to use the following:

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

+2
source

given that you have collected all these lines into an array, the way to do this could be through a foreach clause, for example:

 $res = ""; foreach($strings as $str) { $res.= $str." "; } if(strlen($res > 0)) $res = substr($res,-1); 

this way you can control the process for future changes.

+1
source

All Articles