在以下字符串中,如何刪除括號內的空格?刪除部分字符串中的空格
"The quick brown fox (jumps over the lazy dog)"
所需的輸出:
"The quick brown fox (jumpsoverthelazydog)"
我猜我需要使用正則表達式。我需要將目標放在括號內。以下將刪除括號中括號內的所有內容。
preg_replace("/\(.*?\)/", "", $string)
而且這不起作用:
preg_replace("/\(\s\)/", "", $string)
我承認,正則表達式是不是我的強項。我怎樣才能只針對括號內的內容?
注意:上面的字符串只是爲了演示。實際的字符串和圓括號的位置有所不同。可能出現以下情況:
"The quick brown fox (jumps over the lazy dog)"
"The quick (brown fox jumps) over (the lazy dog)"
"(The quick brown fox) jumps over the lazy dog"
使用ポイズ的回答,我體改供個人使用的代碼:
function empty_parantheses($string) {
return preg_replace_callback("<\(.*?\)>", function($match) {
return preg_replace("<\s*>", "", $match[0]);
}, $string);
}
圓括號可以嵌套嗎?如果是這樣,那應該如何處理? – Chris
@Chris不,他們不能。只有內容(字符串)在括號內。 – akinuri
@akinuri試試我的來源。爲我工作得很好! https://開頭3v4l。org/Wija8 –