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

时间:2015-05-05 04:24:41

标签: php jquery html

下面的代码会像这样回复

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

我需要做的是我需要他们像这样

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

挑战是我无法触及$ str,然后我需要使用' - '来连接单词,如果它们之间有空格,如果使用str_replace空格,它将会像---- nice-apple - 。我怎样才能达到这样的目标('漂亮的苹果'),欣赏。

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

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

3 个答案:

答案 0 :(得分:3)

尝试EXEC sp_configure 'show advanced options', 1 RECONFIGURE GO EXEC sp_configure 'ad hoc distributed queries', 1 RECONFIGURE GO

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

答案 1 :(得分:0)

你需要首先摆脱新的行,然后才能工作。

<?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 ')

答案 2 :(得分:0)

有点棘手。试试 -

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