I'm trying to manipulate an $array:
Array ([0] => General [1] => Custom Title)
Using Implode, I can get the $array
into individual pieces seperated by a space:
<?php $pieces = implode(" ", $array); ?>
Output:
General Custom Title
However, if the array pieces are two words, it doesn't work as I would prefer the output to be:
General Custom-Title
Any ideas?
Replace spaces with hyphens, before you implode.
foreach ($arr as $idx => $val) {
$arr[$idx] = str_replace(" ", "-", $val);
}
$pieces = implode(" ", $arr);
You have to use some string manipulation function for this. I suggest a combination of str_replace
with either array_walk
(or array_map
) or a simple foreach
loop.
<?php
foreach ($myArray as $key => $value) {
$myArray[$key] = str_replace(' ' , '-', $value);
}
$output = implode(' ', $myArray);
?>
$x = array('Hallo X', 'Hallo Y');
echo implode(' ', (array_map(function($e) { return str_replace(' ', '-', $e); }, $x)));
A one liner. The flaw is that you may have %% in the elements of your array, but I doubt that.
$pieces = str_replace('%%', ' ', str_replace(' ', '-', implode('%%', $array)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.