How can I put a '-' between words in this php code?

The following code will be displayed below

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

what i need to do is what i need them to be

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

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

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

echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
?>
+4
source share
3 answers

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

Conclusion:

('nice-apple'),('nice-yellow-banana'),('good-berry')
+3
source

you need to get rid of new lines first, then it will work.

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

$arr = explode(',', str_replace([ "\r\n", "\n" ], "", $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 ')

0
source

Its a little complicated. Try using

$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);
0
source

All Articles