如何在这段代码php中的单词之间加上“ - ”?

Below code will echo like this

('nice apple'),(' nice yellow banana'),(' good berry  ')

what I need to do is that I need them to be like this

('nice-apple'),(' nice-yellow-banana'),(' good-berry  ')

The challenge is that I could not touch $str, and then I need to use '-' to connect words if there is space between them, If use str_replace space, it will be something like ----nice-apple-. how can I achieve something like this ('nice-apple'), appreciate.

<?php
$str="nice apple,
  nice yellow banana,    
  good berry 
 ";

echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
?>

Try str_replace

$str="nice apple,
  nice yellow banana,    
  good berry 
 ";

$str = array_map(function($dr){ return preg_replace('/\s+/', '-', trim($dr));},explode(',',$str));
$str = implode(',',$str);

echo $str = "('" . implode("'),('", explode(',', $str)) . "')";

Output:

('nice-apple'),('nice-yellow-banana'),('good-berry')

you need to get rid of the new lines first then it'll work.

<?php
$str="nice apple,
  nice yellow banana,
  good berry
 ";

$arr = explode(',', str_replace([ "
", "
" ], "", $str));

$arrCount = sizeOf($arr);

for($x = 0; $x < $arrCount; $x++) {
    while (preg_match('/(\w)\s(\w)/', $arr[$x])) {
        $arr[$x] = preg_replace('/(\w)\s(\w)/', '$1-$2', $arr[$x]);
    }
}



echo $str = "('" . implode("'),('", $arr) . "')";
?>

('nice-apple'),(' nice-yellow-banana'),(' good-berry ')

Its bit tricky. Try with -

$str="('nice apple'),(' nice yellow banana'),(' good berry  ')";

$v = explode(',', $str); // generate an array by exploding the string by `,`
foreach($v as $key => $val) {
  $temp = trim(str_replace(["(", "'", ")"], "", $val)); //remove the brackets and trim the string
  $v[$key] = "('".str_replace(" ", "-", $temp)."')"; // place the `-`s
}
$new = implode(",", $v); // implode them again
var_dump($new);