官方手册中:
类似函数还有两个:ltrim() 和 rtrim()。分别处理字符串的左侧、右侧。
trim()的具体实现位于:ext/standard/string.c
/* {{{ proto string trim(string str [, string character_mask]) Strips whitespace from the beginning and end of a string */ PHP_FUNCTION(trim) { php_do_trim(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3); } /* }}} */
/* {{{ php_do_trim * Base for trim(), rtrim() and ltrim() functions. */ static void php_do_trim(INTERNAL_FUNCTION_PARAMETERS, int mode) { zend_string *str; zend_string *what = NULL; ZEND_PARSE_PARAMETERS_START(1, 2) Z_PARAM_STR(str) Z_PARAM_OPTIONAL Z_PARAM_STR(what) ZEND_PARSE_PARAMETERS_END(); ZVAL_STR(return_value, php_trim(str, (what ? ZSTR_VAL(what) : NULL), (what ? ZSTR_LEN(what) : 0), mode)); } /* }}} */
具体实现:
1 /* {{{ php_trim() 2 * mode 1 : trim left 3 * mode 2 : trim right 4 * mode 3 : trim left and right 5 * what indicates which chars are to be trimmed. NULL->default (' v ') 6 */ 7 PHPAPI zend_string *php_trim(zend_string *str, char *what, size_t what_len, int mode) 8 { 9 const char *c = ZSTR_VAL(str); 10 size_t len = ZSTR_LEN(str); 11 register size_t i; 12 size_t trimmed = 0; 13 char mask[256]; 14 15 if (what) { 16 if (what_len == 1) { 17 char p = *what; 18 if (mode & 1) { 19 for (i = 0; i < len; i++) { 20 if (c[i] == p) { 21 trimmed++; 22 } else { 23 break; 24 } 25 } 26 len -= trimmed; 27 c += trimmed; 28 } 29 if (mode & 2) { 30 if (len > 0) { 31 i = len - 1; 32 do { 33 if (c[i] == p) { 34 len--; 35 } else { 36 break; 37 } 38 } while (i-- != 0); 39 } 40 } 41 } else { 42 php_charmask((unsigned char*)what, what_len, mask); 43 44 if (mode & 1) { 45 for (i = 0; i < len; i++) { 46 if (mask[(unsigned char)c[i]]) { 47 trimmed++; 48 } else { 49 break; 50 } 51 } 52 len -= trimmed; 53 c += trimmed; 54 } 55 if (mode & 2) { 56 if (len > 0) { 57 i = len - 1; 58 do { 59 if (mask[(unsigned char)c[i]]) { 60 len--; 61 } else { 62 break; 63 } 64 } while (i-- != 0); 65 } 66 } 67 } 68 } else { 69 if (mode & 1) { 70 for (i = 0; i < len; i++) { 71 if ((unsigned char)c[i] <= ' ' && 72 (c[i] == ' ' || c[i] == ' ' || c[i] == ' ' || c[i] == ' ' || c[i] == 'v' || c[i] == '