如何刪除所有空格但單詞之間有連字符,尤其是當字符串的開頭或結尾有空格時?例如:" Cow jumped over the moon "應該:"Cow-jumped-over-the-moon"我嘗試了以下方法,但我不確定如何去掉字符串前后沒有連字符的空格。$string_with_dashes = str_replace(' ','-',$string);
1 回答

夢里花落0921
TA貢獻1772條經驗 獲得超6個贊
你可以修剪第$string一個
$string = " Cow jumped over the moon ";
$string_with_dashes = str_replace(' ','-',trim($string));
echo $string_with_dashes;
如果你想減少單詞之間的多個空格,你可以匹配 1+ 個水平空格\h+,用連字符替換它們。
$string_with_dashes = preg_replace("/\h+/", "-", trim($string));
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交