14
A
回答
43
你不需要正則表達式的是,使用trim():
$words = ' my words ';
$words = trim($words);
var_dump($words);
// string(8) "my words"
該函數返回空白從一開始就和STR的端部剝離的字符串。
5
爲了完整(因爲這個問題被標記regex
),這裏是一個trim()
重新實現正則表達式:
function preg_trim($subject) {
$regex = "/\s*(\.*)\s*/s";
if (preg_match ($regex, $subject, $matches)) {
$subject = $matches[1];
}
return $subject;
}
$words = ' my words ';
$words = preg_trim($words);
var_dump($words);
// string(8) "my words"
1
出於某種原因,兩個解決上述didnt爲我工作,所以我想出了這個解決方案。
function cleanSpaces($string) {
while(substr($string, 0,1)==" ")
{
$string = substr($string, 1);
cleanSpaces($string);
}
while(substr($string, -1)==" ")
{
$string = substr($string, 0, -1);
cleanSpaces($string);
}
return $string;
}
+0
請注意,雖然這可能會起作用,但遞歸的開銷會使此過程非常緩慢且效率低下。我不知道爲什麼修剪不適合你,因爲它應該適用於任何字符串。 –
相關問題
- 1. MySQL - 刪除給定字符串或字符前後的空格
- 2. 刪除字符串前的空格
- 3. 如何在字符串後添加空格並刪除空格?
- 4. Python正則表達式在字符串前後刪除空格
- 5. ANT:從字符串中刪除前導/後綴空格
- 6. 刪除字符串中所有的空格字符前用PHP
- 7. 如何刪除字符串中的前導字符和尾字符以及多個空格處的空格?
- 8. 刪除字符串,除非有空格
- 9. 如何刪除字符串之間的空格字符?
- 10. 刪除字符串前後的ifnormation
- 11. Java刪除字符串上的空格
- 12. 刪除Java字符串中的空格?
- 13. 刪除字符串「」之外的空格
- 14. 刪除字符串中的空格Javascript
- 15. 刪除字符串中的空格
- 16. 刪除字符串中的空格
- 17. 刪除字符串中的空格
- 18. 刪除XML字符串中的空格
- 19. 刪除字符串內的空格
- 20. Python - 刪除字符串中的空格
- 21. 刪除Python字符串中的空格
- 22. 刪除字符串開頭的空格
- 23. 刪除字符串中的空格
- 24. 刪除字符串中的空格
- 25. Java - 刪除字符串後的空格(如果存在)
- 26. 刪除字符串中僅存在於分隔符前後的所有空格
- 27. 從長字符串空格中刪除單個空格字符
- 28. 如何從字符串中刪除雙字符和空格
- 29. 如何刪除以前的字符串
- 30. 刪除字符串中最後一個空格後的最後一個字符
這是怎麼回事?我仍然在絃樂之後看到我的空白處。任何提示?任何人 ? – ihue
也許他們不是真的空白。我遇到了來自Office Word文本的這個問題。 –