{php string function}
php operation string
In Web applications, the interaction between users and the system is basically carried out using text, so the system's processing of text information, that is, strings, is very important. There are many operations on text strings, and this section will introduce them one by one.
3.1.1 Remove spaces and other special symbols
Sometimes, you need to remove spaces or other meaningless symbols from a string. For example, in an e-commerce application, when the user fills in the content of the order (such as a contact address), he may enter some spaces, periods and other characters. The system hopes to remove them before storing, leaving only meaningful information. In order to solve problems similar to the above requirements, PHP4 and above provide 4 functions for removing special symbols in strings.
String trim (string str [, string charlist]): Remove spaces or other special symbols at the beginning and end of string str.
String ltrim (string str [, string charlist]): Remove spaces or other special symbols at the beginning of string str.
String rtrim (string str [, string charlist]): Remove spaces or other special symbols at the end of string str.
String chop (string str [, string charlist]): The function is the same as rtrim().
The first parameter str of the above function is the string to be operated, and the second optional parameter charlist specifies the special symbols that you want to remove. When defaulted, the default value is to remove the following characters: spaces (" "), Tab character (t), line feed character (n), carriage return character (r), null value (
The following uses trim() as an example to illustrate the use of the above functions.1
2 3 $init_str = ", No. 8, Jingshi Road, Jinan City, Shandong Province. "; //Contains a space before and after
4 echo $init_str."#
5 $trimmed_str = trim($init_str); //"No. 8, Jingshi Road, Jinan City, Shandong Province 1."
6 echo $trimmed_str."#
7 $trimmed_str = trim($init_str,', .');//"No. 8 Jingshi Road, Jinan City, Shandong Province 1". Note that the second parameter includes 3 characters.
8 echo $trimmed_str."#
9 $trimmed_str = trim($init_str,', .0..9'); //"No. 8, Jingshi Road, Jinan City, Shandong Province". 0..9 means to remove all numeric characters
10 echo $trimmed_str."#
11 ?>
Line 3 defines a string variable with spaces and commas at the beginning and periods and spaces at the end;
Line 5 uses the trim() function without the second parameter to remove the space symbols at the beginning and end;
Line 7 uses the trim() function with the second parameter to remove the characters contained in the second parameter at the beginning and end, that is, the spaces, commas and periods at the beginning and end are removed.
The "0..9" in the second parameter of trim() on line 9 indicates that all characters within the ASC code range of 0 and 9 will be removed.
The use of ltrim() and rtrim() is similar to trim(), and chop() is actually an alias of rtrim(). Its function is the same as rtrim(), which will not be described again.
3.1.2 Adding and removing backslashes
In many applications, such as when generating SQL statements (SQL statements will be introduced in the second part), it is necessary to add the escape character ‘’, which is quite troublesome to construct manually. In order to solve similar problems, PHP provides functions that automatically add or remove escape characters from strings.
String addcslashes (string str, string charlist): The first parameter str is the original string to be operated, and the second parameter charlist indicates which characters of the original string need to be preceded by the character ‘’.
String stripcslashes (string str): Remove the ‘’ from the string.
For the use of both, please refer to the code below.
1
2 3 $init_str = "select * from Books where name = 'PHP Manual'";
4 echo $init_str."#
5 $new_str = addcslashes($init_str,"'");
6 echo $new_str."#
7 $init_str2 = stripcslashes($new_str);
8 echo $init_str2."#
";
9 ?>
代码在第5行在$init_str中的‘’’前加上了‘\’,又在第9行将其去掉。
3.1.3 生成HTML元素
HTML元素的书写非常麻烦,下面简单列出一些常用字符在HTML中的表示方式。
'&':'&'
双引号‘"’:'"'
单引号‘'’:'''
'<' :'<'
'>' :'>'
此处,称'&'等为HTML元素,'&' 等为其显示字符串。例如,若想在页面上的显示 “链接”,HTML应写为“<a href='test'>Test</a>”,否则,将只在页面上显示一个链接信息。
PHP提供了下面的函数来自动转化HTML元素。
string htmlspecialchars(string str [, int quote_style [, string charset]]):把一些常用的HTML元素转换为显示字符串。
string htmlentities(string str [, int quote_style [, string charset]]):把所有的HTML元素转换为显示字符串。
string html_entity_decode(string str [, int quote_style [, string charset]]):把显示字符串转化为HTML元素。
上面函数中,参数str表示原始字符串;可选参数quote_style确定是否转换双引号和单引号,取值范围为{ ENT_COMPAT , ENT_QUOTES , ENT_NOQUOTES},分别表示只转换双引号、全转换、全不转换,缺省时默认值为ENT_COMPAT;第3个参数charset指定了转换中所用的字符集。PHP4及以上版本所支持的字符集参考表3.1。
表3.1 PHP4及以上版本支持的字符集
字 符 集
说 明
ISO-8859-1
西欧字符集
ISO-8859-15
西欧字符集扩展
UTF-8
兼容ASCII的宽字节字符集
cp1252
西欧字符集,Windows系统默认
BIG5
繁体中文,用于中国台湾省
GB2312
简体中文,用于中国大陆
BIG5-HKSCS
繁体中文扩展,用于中国香港
Shift_JIS
日文
EUCJP
日文
下面的示例中,首先使用htmlentities()函数得到一个HTML语句的显示字符串,然后再用html_entity_decode()函数重新把显示字符串转回HTML元素。运行结果如图3.1所示。
1
2
3 $orig = "我正在学习! ";
4 $a = htmlentities($orig,ENT_COMPAT,"GB2312");
5 $b = html_entity_decode($a);
6 echo $a; // I'll "walk" the <b>dog</b> now
7 echo $b; // I'll "walk" the dog now
8 ?>
图3.1 PHP生成HTML元素示例
注意
函数html_entity_decode()只支持PHP4.0.3及以上版本。
除上面所提到的3个函数之外,用于HTML元素操作的函数还包括nl2br()、get_html_translation_table()等,功能与上述函数类似,本书不再一一详述。
3.1.4 分解字符串
分解字符串是指把一个字符串通过特殊的符号分解为许多子串。例如,时间字符串“2005-01-01 12:59:59”可以利用符号“-”、空格和“:”分解为年月日时分秒具体的值。PHP提供了下列函数完成类似功能:
array split(string pattern, string str [, int limit])
Among them, the parameter pattern specifies the symbol as the decomposition identifier; str is the original string to be operated; the third optional parameter limit is the maximum value of the number of substrings returned, and by default, all are returned. The return value of the function is an array, which will be introduced in Section 3.2. Here, the function return value can be temporarily understood as multiple substrings.
The following example can decompose the string "2005-01-01 12:59:59" into substrings of year, month, day, hour, minute and second.
1
2
3 $date = "2005-01-01 12:59:59";
4 list ($year,$month,$day,$hour,$minite,$second) = split ('[- :]',$date);
5 echo "{$year}year{$month}month{$day}day{$hour}hour{$minite}minute{$second}second
n";
6 ?>
The above example will output "January 1, 2005 12:59:59". Line 4 uses the split function to decompose the time. The decomposed identifiers include "-", spaces and ":", which are output on line 5.
In addition to split, functions with similar functions include preg_split(), explode(), implode(), chunk_split() and wordwrap(), etc.
3.1.5 Format string
Format string is used to output text containing many variables in a certain format. It is the most commonly used operation. PHP's fprintf() function completes this function, and readers who are accustomed to using C language must be familiar with it. The function prototype is:
string sprintf(string format, mixed [args]...)
The format parameter is the converted format. Each variable specifies its format with the characters after "%". The following parameters correspond to the "%" in the format. The following example formats the decimal part of a floating point number.
1
2
3 $name="Zhang San";
4 $money1 = 68.75;
5 $money2 = 54.35;
6 $money = $money1 + $money2;
7 // At this time the value of variable $money is "123.1";
8 $formatted = sprintf ("%s has ¥%01.2f.",$name, $money);
9 echo $formatted; //Zhang San has ¥123.10.
10 ?>
Line 6 uses arithmetic operations to obtain the value of $money as 123.1; and line 8 uses %01.2 in sprintf to define its format to display two decimal places.
In addition to sprintf(), functions commonly used to format data include printf(), sprintf(), sscanf(), fscanf(), vsprintf(), number_format(), etc.
3.1.6 Obtaining and replacing substrings
Getting a substring means getting a continuous part of a string. For example, obtain the time string from the string "2005-01-01 12:59:59". PHP provides two functions to obtain or replace a certain part of a string:
String substr (string str, int start [, int length]): Get the substring. The first parameter str is the string to be operated on. The second parameter start indicates the starting position of the substring in the total string. The third optional parameter specifies the length of the obtained substring. If it is a positive number, it indicates that the substring is taken from start to the right, otherwise it is taken from the left; by default, the default value is from start to the end of the string.
String substr_replace (string str, string replacement, int start [, int length]): Replace on the basis of acquisition, that is, replace the acquired substring with its second parameter replacement.
In the following example, substr() is first used to obtain the time information of the string "2005-01-01 12:59:59", and then the substr_replace() function is used to change the year information to "2006":
1
2
3 $date = "2005-01-01 12:59:59";
4 $time=substr($date,11,8); //The starting position of the substring "12:59:59" is 11 and the length is 8
5 echo "time:$time
";
6 $new_date=substr_replace($date,"2006",0,4);
7 echo "new date:$new_date";
8 ?>
3.1.7 Positioning characters
Positioning characters refers to finding the position where a certain character first appears in a string. The function strpos() can complete this function.
int strpos (string str, char needle): The first parameter str is the string to be processed, and the second parameter needle is the character to be found. In the following example, an email address is processed. First, strpos() is used to find the character "@", and then the user name is obtained by combining the substring acquisition function strstr().
1
2
3 $email = "zhangsan@php.net";
4 $i=strpos($email,'@');
5 $name=substr($email,0,$i);
6 echo $name;
7 ?>
In the 4th line of the example, strpos() is used to obtain the position of the character '@', and then in the 5th line, substr() is used to obtain the username substring information.
3.1.8 Find the string length
Finding the length of a string is also a common operation. The function used is strlen(): int strlen (string str).
This function is very simple, returning the length of the string str. Still using the example in the previous section, replace the user's name from the email string, that is, change it to lisi@php.net.
1
2
3 $email = "zhangsan@php.net";
4 $i=strpos($email,'@');
5 $name=substr($email,0,$i);
6 $email=substr_replace($email,"lisi",0,strlen($name));
7 echo $email;
8 ?>
3.1.9 Get ASCII code
Converting characters to ASCII encoding is sometimes very useful in practical applications. For example, strings are stored in binary form in the database, and when the data acquisition function needs to return an ASCII code string, it needs to be converted into a string. show. There are two functions provided by PHP for converting ASCII codes and characters.
String chr (int ascii): Convert ASCII code to string.
int ord (string string): Convert the string into ASCII code.
Please refer to the following example for using both.
1
2
3 $letter = chr(65); //A
4 $ascii=ord('A'); //65
5 echo $letter;
6 echo $ascii;
7 ?>
3.1.10 Compare strings
The comparison rule of strings is according to the dictionary sorting method, the ones in the front are smaller than the ones in the back. As in an English dictionary, later entries are larger than earlier entries. PHP functions to implement string comparison are as follows.
int strncmp (string str1, string str2[, int len]): The first two parameters of the function are the two strings to be compared. The third optional parameter can specify how many strings from the beginning you want to compare the two. character. If str1>str2, the function returns a positive number; when str1=str2, it returns 0; when str1 1 2 3 $str1="China"; 4 $str2="Beijing"; 5 $i=strcmp($str1,$str2); 6 echo $i; //1 7 ?> In addition to strcmp(), functions with string comparison or sorting functions are strcasecmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort(). 3.1.11 Case conversion To compare whether two strings are equal without case sensitivity, just using the strcmp() function in the previous section will not work. In this case, the two strings can be converted to uppercase or lowercase at the same time, and then compared. That’s it. For example, this is often needed when determining the username and password for website login (when case-insensitive). The PHP function that implements string case conversion is as follows. String strtolower (string str): Convert str to lowercase. String strtoupper (string string): Convert str to uppercase. String ucfirst(string str): Convert the first character of str to uppercase. String ucwords (string str): Convert the first letter of each word in str to uppercase. Refer to the example below. 1 2 3 $str1="shandong province"; 4 $str2="China"; 5 $str1=ucwords($str1); 6 echo $str1; //Shangdong Province 7 $str1=strtoupper($str1); 8 echo $str1; //SHANGDONG PROVINCE 9 $str2=strtolower($str2); 10 echo $str2; //china 11 ?> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ PHP字符串函数分类 1查找字符位置函数: ']):去除HTML和PHP标记 ');
strpos($str,search,[int]):查找search在$str中的第一次位置从int开始;
stripos($str,search,[int]):函数返回字符串在另一个字符串中第一次出现的位置。该函数对大小写不敏感
strrpos($str,search,[int]):查找search在$str中的最后一次出现的位置从int
2、提取子字符函数(双字节)
submit($str,int start[,int length]):从$str中strat位置开始提取[length长度的字符串]。
strstr($str1,$str2):从$str1(第一个的位置)搜索$str2并从它开始截取到结束字符串;若没有则返回FALSE。
stristr() 功能同strstr,只是不区分大小写。
strrchr() 从最后一次搜索到的字符处返回;用处:取路径中文件名
3、替换字符串
str_replace(search,replace,$str):从$str中查找search用replace来替换
str_irreplace(search,replace,$str):
strtr($str,search,replace):这个函数中replace不能为"";
substr_replace($Str,$rep,$start[,length])$str原始字符串,$rep替换后的新
字符串,$start起始位置,$length替换的长度,该项可选
4、字符长度
int strlen($str)
5、比较字符函数
int strcmp($str1,$str2):$str1>=<$str2分别为正1,0,-1(字符串比较)
strcasecmp() 同上(不分大小写)
strnatcmp("4","14") 按自然排序比较字符串
strnatcasecmp() 同上,(区分大小写)
6、分割成数组函数
str_split($str,len):把$str按len长度进行分割返回数组
split(search,$str[,int]):把$str按search字符进行分割返回数组int是分割几次,后面的将不分割
expload(search,$str[,int])
7、去除空格:ltrim、rtrim、trim
8、加空格函数
chunk_split($str,2);向$str字符里面按2个字符就加入一个空格;
9、chr、ord--返回指定的字符或ascii
10、HTML代码有关函数
nl2br():使\n转换为<br>。
strip_tags($str[,'
在$str中所有HTML和PHP代码将被去除,可选参数为html和PHP代码作用是将保留
可选参数所写的代码。
如:echo strip_tags($text, '
htmlspecialchars($str[,参数]):页面正常输出HTML代码参数是转换方式
11、字符大小写转换函数
strtolower($str) 字符串转换为小写
strtoupper($str) 字符串转换为大写
ucfirst($str) 将函数的第一个字符转换为大写
ucwords($str) 将每个单词的首字母转换为大写
12、数据库相关函数
addslashes($str):使str内单引号(')、双引号(")、反斜线(\)与 NUL
字符串转换为\',\",\\。
magic_quotes_gpc = On 自动对 get post cookie的内容进行转义
get_magic_quotes_gpc()检测是否打开magic_quotes_gpc
stripslashes() 去除字符串中的反斜杠
13、连接函数
implode(str,$arr) 将字符串数组按指定字符连接成一个字符串;implode()函数有个别名函数join
addcslashes —— 为字符串里面的部分字符添加反斜线转义字符
addslashes —— 用指定的方式对字符串里面的字符进行转义
bin2hex —— 将二进制数据转换成十六进制表示
chr —— 返回一个字符的ASCII码
chunk_split —— 按一定的字符长度将字符串分割成小块
convert_cyr_string —— 将斯拉夫语字符转换为别的字符
convert_uudecode —— 解密一个字符串
convert_uuencode —— 加密一个字符串
count_chars —— 返回一个字符串里面的字符使用信息
crc32 —— 计算一个字符串的crc32多项式
crypt —— 单向散列加密函数
explode —— 将一个字符串用分割符转变为一数组形式
fprintf —— 按照要求对数据进行返回,并直接写入文档流
get_html_translation_table —— 返回可以转换的HTML实体
html_entity_decode —— htmlentities ()函数的反函数,将HTML实体转换为字符
htmlentities —— 将字符串中一些字符转换为HTML实体
htmlspecialchars_decode —— htmlspecialchars()函数的反函数,将HTML实体转换为字符
htmlspecialchars —— 将字符串中一些字符转换为HTML实体
implode —— 将数组用特定的分割符转变为字符串
join —— 将数组转变为字符串,implode()函数的别名
levenshtein —— 计算两个词的差别大小
localeconv —— 获取数字相关的格式定义
ltrim —— 去除字符串左侧的空白或者指定的字符
md5_file —— 将一个文件进行MD5算法加密
md5 —— 将一个字符串进行MD5算法加密
metaphone —— 判断一个字符串的发音规则
money_format —— 按照参数对数字进行格式化的输出
nl_langinfo —— 查询语言和本地信息
nl2br —— 将字符串中的换行符“\n”替换成“
”
number_format —— 按照参数对数字进行格式化的输出
ord —— 将一个ASCII码转换为一个字符
parse_str —— 把一定格式的字符串转变为变量和值
print —— 用以输出一个单独的值
printf —— 按照要求对数据进行显示
quoted_printable_decode —— 将一个字符串加密为一个8位的二进制字符串
quotemeta —— 对若干个特定字符进行转义
rtrim —— 去除字符串右侧的空白或者指定的字符
setlocale —— 设置关于数字,日期等等的本地格式
sha1_file —— 将一个文件进行SHA1算法加密
sha1 —— 将一个字符串进行SHA1算法加密
similar_text —— 比较两个字符串,返回系统认为的相似字符个数
soundex —— 判断一个字符串的发音规则
sprintf —— 按照要求对数据进行返回,但是不输出
sscanf —— 可以对字符串进行格式化
str_ireplace —— 像str_replace()函数一样匹配和替换字符串,但是不区分大小写
str_pad —— 对字符串进行两侧的补白
str_repeat —— 对字符串进行重复组合
str_replace —— 匹配和替换字符串
str_rot13 —— ROT13 encrypts the string
str_shuffle - Randomly sort the characters in a string
str_split —— Split a string into an array according to the character spacing
str_word_count —— Get the English word information in the string
strcasecmp - compares strings, case-insensitive
strchr - Alias for the strstr() function that returns a portion of a string by comparison
strcmp - Compare string sizes
strcoll – Compare string sizes based on local settings
strcspn - Returns the value of the continuous non-matching length of characters
strip_tags - Remove HTML and PHP code from a string
stripcslashes - anti-escape the string processed by the addcslashes() function
stripos - Find and return the position of the first match, matching is not case sensitive
stripslashes - anti-escaping the strings processed by the addslashes() function
stristr - Returns parts of a string by comparison, case-insensitive
strlen - Get the encoded length of a string
strnatcasecmp - Compare strings using natural sorting, case-insensitive
strnatcmp - Compare strings using natural sorting
strncasecmp - compares the first N characters of a string, case-insensitive
strncmp - Compare the size of the first N characters of a string
strpbrk - Returns parts of a string
by comparison
strpos - Find and return the position of the first match
strrchr - Returns a portion of a string
by comparing it from back to front
strrev - reverse all the letters in the string
strripos - search from the back to the front and return the position of the first match, the match is not case sensitive
strrpos —— Search from back to front and return the position of the first matching item
strspn —— Match and return the value of the length of consecutive occurrences of characters
strstr - Returns part of a string
by comparison
strtok —— Split a string using specified characters
strtolower - Convert string to lowercase
strtoupper - Convert a string to uppercase
strtr - Compare and replace strings
substr_compare - Compare strings after interception
substr_count —— Count the number of occurrences of a certain character segment in a string
substr_replace - Replace some characters in the string
substr - intercept the string
trim——Remove whitespace or specified characters
on both sides of the string
ucfirst - Convert the first letter of the given string to uppercase
ucwords - Capitalize the first letter of each English word in the given string
vfprintf - returns data as required and writes it directly to the document stream
vprintf - display data as required
vsprintf - returns the data as required, but does not output
wordwrap - Split a string according to a certain character length