php---字符串操作
时间:2006-08-03 来源:cnscn2008
.string addcslashes(string str, string charlist) //像C那样使用反斜线转义字符串中的字符
返回字符串, 该字符串在属于参数charlist列表中的字符前都加上了反斜线。 些函数对\n、\r等进行转义。像C那样,ASCII码低于32及高于126的字符均转换成使用八进制表示
当选择对字符0、a、b、f、n、r、t和v进行转义时需要小心, 它们将被转换成\0、\a、\b、\f、\n、\r、\t和\v. 在PHP中,只有\0(NULL)、\r(回车符)、\n(换行符)和\t(分隔符)是预定义的转义序列。
.string addslashes ( string str ) //使用反斜线引用字符串
返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。
一个使用 addslashes() 的例子是当你要往数据库中输入数据时。例如,将名字 O'reilly 插入到数据库中,这就需要对其进行转义。大多数据库使用 \ 作为转义符:O\'reilly。这样可以将数据放入数据库中,而不会插入额外的 \。当 PHP 指令 magic_quotes_sybase 被设置成 on 时,意味着插入 ' 时将使用 ' 进行转义。
默认情况下,PHP 指令 magic_quotes_gpc 为 on,它主要是对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。
示例
$str = "Is your name O'reilly?";
// 输出:Is your name O\'reilly?
echo addslashes($str);
.string chr ( int ascii ) //返回相对应于 ascii 所指定的单个字符。
$str = "The string ends in escape: ";
$str .= chr(27); /* 在 $str 后边增加换码符 */
/* 通常这样更有用 */
$str = sprintf("The string ends in escape: %c", 27);
.string chunk_split ( string body [, int chunklen [, string end]] ) //将字符串分割成小块
使用此函数将字符串分割成小块非常有用。例如将 base64_encode() 的输出转换成符合 RFC 2045 语义的字符串。它会在每 chunklen(默认为 76)个字符后边插入 end(默认为“\r\n”)。此函数会返回新的字符串,而不会修改原有字符串。
// 使用 RFC 2045 语义格式化 $data
$new_string = chunk_split(base64_encode($data));
.array explode ( string separator, string string [, int limit] ) //使用一个字符串分割另一个字符串
此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 separator 作为边界点分割出来。如果设置了 limit 参数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。
如果 separator 为空字符串(""),explode() 将返回 FALSE。如果 separator 所包含的值在 string 中找不到,那么 explode() 将返回包含 string 单个元素的数组。
如果 limit 参数是负数,则返回除了最后的 limit 个元素外的所有元素。此特性是 PHP 5.1.0 中新增的。
由于历史原因,虽然 implode() 可以接收两种参数顺序,但是 explode() 不行。你必须保证 separator 参数在 string 参数之前才行。
注: 参数 limit 是在 PHP 4.0.1 中加入的。
例子 1. explode() 示例
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
例子 2. limit 参数示例
$str = 'one|two|three|four';
// 正数的 limit
print_r(explode('|', $str, 2));
// 负数的 limit
print_r(explode('|', $str, -1));
以上示例将输出:
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)
.int fprintf ( resource handle, string format [, mixed args [, mixed ...]] ) //Write a formatted string to a stream
Write a string produced according to format to the stream resource specified by handle. format is described in the documentation for sprintf().
Returns the length of the outputted string.
See also: printf(), sprintf(), sscanf(), fscanf(), vsprintf(), and number_format().
Examples
例子 1. fprintf(): zero-padded integers
if (!($fp = fopen('date.txt', 'w')))
return;
fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// will write the formatted ISO date to date.txt
例子 2. fprintf(): formatting currency
if (!($fp = fopen('currency.txt', 'w')))
return;
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// will write "123.10" to currency.txt
echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote
.string implode ( string glue, array pieces ) //Join array elements with a string
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
.string money_format ( string format, float number ) //Formats a number as a currency string
money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.
注: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
The format specification consists of the following sequence:
a % character
optional flags
optional field width
optional left precision
optional right precision
a required conversion character
Flags. One or more of the optional flags below can be used:
=f
The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space.
^
Disable the use of grouping characters (as defined by the current locale).
+ or (
Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.
!
Suppress the currency symbol from the output string.
-
If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).
Field width.
w
A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).
Left precision.
#n
The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.
If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.
To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.
Right precision .
.p
A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.
Conversion characters .
i
The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).
n
The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: DM1.234,56).
%
Returns the % character.
注: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.
Characters before and after the formatting string will be returned unchanged.
例子 1. money_format() Example
We will use different locales and format specifications to illustrate the use of this function.
.string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] ) //Format a number with grouped thousands
number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):
If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.
If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.
If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.
Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.
例子 1. number_format() Example
For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :
.int ord ( string string ) //Return ASCII value of character
Returns the ASCII value of the first character of string. This function complements chr().
例子 1. ord() example
$str = "\n";
if (ord($str) == 10) {
echo "The first character of \$str is a line feed.\n";
}
.void parse_str ( string str [, array &arr] ) //Parses the string into variables
Parses str as if it were the query string passed via a URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as array elements instead.
注: Support for the optional second parameter was added in PHP 4.0.3.
注: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from outside of PHP.
注: The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
.string sprintf ( string format [, mixed args [, mixed ...]] ) //Return a formatted string
Returns a string produced according to the formatting string format.
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
1. An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
2. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
3. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
4. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
5. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string.
6. A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required.
b - the argument is treated as an integer, and presented as a binary number.
c - the argument is treated as an integer, and presented as the character with that ASCII value.
d - the argument is treated as an integer, and presented as a (signed) decimal number.
e - the argument is treated as scientific notation (e.g. 1.2e+2).
u - the argument is treated as an integer, and presented as an unsigned decimal number.
f - the argument is treated as a float, and presented as a floating-point number (locale aware).
F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
o - the argument is treated as an integer, and presented as an octal number.
s - the argument is treated as and presented as a string.
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
As of PHP 4.0.6 the format string supports argument numbering/swapping. Here is an example:
例子 1. Argument swapping
This might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:
例子 2. Argument swapping
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:
例子 3. Argument swapping
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:
例子 4. Argument swapping
See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().
Examples
例子 5. printf(): various examples
The printout of this program would be:
%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'
例子 6. printf(): string specifiers
The printout of this program would be:
[monkey]
[ monkey]
[monkey ]
[0000monkey]
[####monkey]
[many monke]
例子 7. sprintf(): zero-padded integers
例子 8. sprintf(): formatting currency
例子 9. sprintf(): scientific notation
.mixed str_ireplace ( mixed search, mixed replace, mixed subject [, int &count] ) //Case-insensitive version of str_replace().
This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of eregi_replace() or preg_replace() with the i modifier.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.
例子 1. str_ireplace() example
");
?>
This function is binary safe.
.string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]] ) //Pad a string to a certain length with another string
This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
If the value of pad_length is negative or less than the length of the input string, no padding takes place.
例子 1. str_pad() example
.array str_split ( string string [, int split_length] ) //Convert a string to an array
Converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.
FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
Output may look like:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
$str = "Hello Friend";
echo $str{0}; // H
echo $str{8}; // i
// Creates: array('H','e','l','l','o',' ','F','r','i','e','n','d')
$arr1 = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
.int strcmp ( string str1, string str2 ) //Binary safe string comparison
Returns str1 is less than
str2; > 0 if str1
is greater than str2, and 0 if they are
equal.
Note that this comparison is case sensitive.
.int strcasecmp ( string str1, string str2 ) //Binary safe case-insensitive string comparison
Returns 0 if str1 is greater than str2, and 0 if they are equal.
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
相关阅读 更多 +