我想在PHP中使用preg_replace
來替換字符串末尾的空格而不用任何內容。我創建了一個龐大的單詞數據庫,最終還是有一些單詞得到了額外的空白空間。使用preg_replace刪除字符串末尾的額外空間
4
A
回答
3
爲什麼不使用TRIM()http://php.net/manual/en/function.trim.php
8
您應該使用rtrim
代替。它將刪除字符串末尾的多餘空格,並且比使用preg_replace
更快。 。
$str = "This is a string. ";
echo rtrim($str);
速度比較 - preg_replace
v trim
// Our string
$test = 'TestString ';
// Test preg_replace
$startpreg = microtime(true);
$preg = preg_replace("/^\s+|\s+$/", "", $test);
$endpreg = microtime(true);
// Test trim
$starttrim = microtime(true);
$trim = rtrim($test);
$endtrim = microtime(true);
// Calculate times
$pregtime = $endpreg - $startpreg;
$trimtime = $endtrim - $starttrim;
// Display results
printf("preg_replace: %f<br/>", $pregtime);
printf("rtrim: %f<br/>", $trimtime);
結果
的preg_replace:0.000036
RTRIM:0.000004
正如你所看到的,rtrim
實際上是nine times更快。
0
用了preg_replace,你想:
$s = ' okoki efef ef ef
';
print('-'.$s.'-<br/>');
$s = preg_replace('/\s+$/m', '', $s);
print('-'.$s.'-');
相關問題
- 1. 從字符串末尾刪除^符號
- 2. 刪除字符串末尾的'/'?
- 3. 刪除字符串末尾的新行
- 4. 刪除字符串末尾的逗號
- 5. 從字符串末尾刪除.pdb
- 6. 如何從Python中的字符串末尾刪除空格?
- 7. 如何刪除字符串末尾的空格?
- 8. 如何從字符串的末尾刪除子字符串
- 9. 從字符串數組中的字符串末尾刪除「,」
- 10. 查找字符串並在末尾添加額外的
- 11. 刪除每個字符串末尾的特定字符
- 12. 刪除字符串末尾的破折號字符
- 13. R:刪除字母數字字符串末尾的零字
- 14. PHP:使用正則表達式從字符串中刪除額外空間
- 15. 字符串末尾多餘的空格
- 16. 如何從字符串末尾刪除字符
- 17. 從字符串末尾刪除已知字符
- 18. 從字符串末尾刪除特殊字符
- 19. 從字符串末尾刪除n個字符
- 20. 刪除字符串C末尾的數字#
- 21. 空字符串在末尾有「\ u0000」
- 22. 使用preg_replace刪除某個字符周圍的空白字符
- 23. C:試圖從字符串末尾刪除換行符
- 24. 刪除空字符串列的空間
- 25. 如何動態刪除Javascript中的字符串中的額外空間?
- 26. 尋找使用preg_replace從我的字符串中刪除字符
- 27. 刪除出現在字符串末尾的標籤
- 28. 如何刪除substr字符串末尾的 ?
- 29. PHP:從字符串末尾的URL中刪除'print /'
- 30. Javascript只在字符串末尾刪除多餘的下劃線
爲什麼不我想想。謝謝你們倆 – daron 2011-01-24 21:51:41