Home  >  Article  >  Backend Development  >  php string functions

php string functions

巴扎黑
巴扎黑Original
2016-11-24 10:49:331136browse

1查找字符位置函数:
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[,'

']):去除HTML和PHP标记 
在$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 - Add backslash escape characters to some characters in the string
addslashes - Escape the characters in the string in a specified way
bin2hex - Convert binary data to hexadecimal representation
chr —— Return the ASCII code of a character
chunk_split —— Split the string into small pieces according to a certain character length
convert_cyr_string —— Convert Cyrillic characters to other characters
convert_uudecode —— Decrypt a string
convert_uuencode —— Encrypt a string
count_chars - Return the character usage information in a string
crc32 - Calculate the crc32 polynomial of a string
crypt - One-way hash encryption function
explode - Convert a string using delimiters In the form of an array
fprintf - Returns data as required and writes it directly into the document stream
get_html_translation_table - Returns HTML entities that can be converted
html_entity_decode - The inverse function of htmlentities () function, converts HTML entities into characters
htmlentities —— Convert some characters in the string to HTML entities
htmlspecialchars_decode —— The inverse function of htmlspecialchars() function, convert HTML entities into characters
htmlspecialchars —— Convert some characters in the string to HTML entities
implode —— Will Convert an array into a string using a specific separator
join - Convert an array into a string, an alias of the implode() function
levenshtein - Calculate the difference between two words
localeconv - Get number-related format definitions
ltrim —— Remove the blank space or specified characters on the left side of the string
md5_file —— Encrypt a file with the MD5 algorithm
md5 —— Encrypt a string with the MD5 algorithm
metaphone —— Determine the pronunciation rules of a string
money_format — — Output of numbers formatted according to parameters
nl_langinfo — Query language and locale information
nl2br — Replace newline characters “/n” in strings with “

number_format — According to parameters Formatted output of numbers
ord - Convert an ASCII code to a character
parse_str - Convert a string in a certain format into variables and values ​​
print - Used to output a single value
printf - Follow Requires data to be displayed
quoted_printable_decode - Encrypts a string into an 8-bit binary string
quotemeta - Escapes several specific characters
rtrim - Removes the blanks or specified characters on the right side of the string
setlocale - Set local formats for numbers, dates, etc.
sha1_file - Encrypt a file with SHA1 algorithm
sha1 - Encrypt a string with SHA1 algorithm
similar_text - Compare two strings and return what the system thinks Number of similar characters
soundex —— Determine the pronunciation rules of a string
sprintf —— Return the data as required, but do not output
sscanf —— You can format the string
str_ireplace —— Like the str_replace() function Match and replace strings, but not case sensitive
str_pad - pad both sides of the string
str_repeat - Repeat the string combination
str_replace - Match and replace the string
str_rot13 - Repeat the string ROT13 encryption processing
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 —— Match the characters String size comparison, case-insensitive
strchr - Alias ​​of the strstr() function that returns part of a string through comparison
strcmp - String size comparison
strcoll - String size comparison based on local settings
strcspn - Returns the value of the continuous non-matching length of characters
strip_tags - Removes HTML and PHP code in a string
stripcslashes - Unescapes the string processed by the addcslashes() function
stripos - Find and return The position of the first match, the match is not case-sensitive
stripslashes - anti-escaping the addslashes() function to escape the processed string
stristr - returns a part of the string through comparison, the comparison is not case-sensitive
strlen - Get the encoded length of a string
strnatcasecmp - Use natural sorting to compare strings, case-insensitive
strnatcmp - Use natural sorting to compare strings
strncasecmp - Compare strings Compare the first N characters of a string, case-insensitive
strncmp - Compare the size of the first N characters of a string
strpbrk - Return a part of a string through comparison
strpos - Find and return the first match The position of the item
strrchr - Returns the part of a string by comparing from back to front
strrev - Arranges all letters in the string in reverse order
strripos - Searches from back to front and returns the position of the first matching item , matching 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 - Return a part of a string by comparison
strtok - Use the specified number of characters to split the string
strtolower —— Convert the string to lowercase
strtoupper —— Convert the string to uppercase
strtr —— Compare and replace the string
substr_compare —— Compare the string after interception
substr_count —— Calculate the number of occurrences of a certain character segment in a string
substr_replace —— Replace some characters in the string
substr —— Truncate the string
trim —— Remove the blanks or specified characters on both sides of the string
ucfirst —— Convert the first letter of the given string to uppercase
ucwords - Convert the first letter of each English word in the given string to uppercase
vfprintf - Return the data as required and write it directly Document flow
vprintf - displays data as required
vsprintf - returns data as required, but does not output
wordwrap - splits strings according to a certain character length

1, a function range that quickly creates arrays ()

For example, the range() function can quickly create a number array from 1 to 9:

$numbers=range(1,9); //Use range to directly create a total of 9 numbers from 1 to 9 An array starting with "1" and ending with "9".
echo $numbers[1]; //Output the second created array value: 2; echo $numbers[0]; then enter the first value: 0.
?>

Of course, using range(9,1) creates a number array from 9 to 1. At the same time, range() can also create a character array from a to z:

$numbers=range(a,z);
foreach ($numbers as $mychrs) //Traverse the $numbers array, each The current cell value of the second loop is assigned to $mychrs
echo $mychrs." "; //output a b c d e f g h i j k l m n o p q r s t u v w x y z
?>

//foreach is a convenient way to traverse the array. foreach can only be used for arrays. When trying to An error will occur when using it with other data types or an uninitialized variable. It has two formats:

foreach (array_expression as $value) statementforeach (array_expression as $key => $value) statement
The first one Format iterates over the given array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop). The second format does the same thing, except that the key name of the current unit will also be assigned to the variable $key in each loop


Pay attention to case when using character arrays, such as range(A,z) and range( a, Z) are different. The

range() function also has a third parameter, which is used to set the step size. For example, the array elements created by range(1,9,3) are: 1, 4, 7

2, conventional in PHP Sorting of arrays

Generally, each element in an array is represented by characters or numbers, so the array elements can be arranged in ascending order. This function is sort(). For example:

$people=array('name','sex','nation','birth');
foreach ($people as $mychrs)
echo $mychrs." ";
sort ($people);
echo "
---After sorting---
";
foreach ($people as $mychrs)
echo $mychrs." ";
?> ;

The array elements sorted in ascending order are displayed as birth name nation sex. Of course, the sort() function is case-sensitive (the order of letters from large to small is: A...Z...a...z)

Sort( ) function also has a second parameter, which is used to indicate whether the ascending rule is used to compare numbers or strings. For example:

echo "---Sort in ascending numerical order---
";
$num2=array('26','3',);
sort($num2 ,SORT_NUMERIC);
foreach ($num2 as $mychrs)
echo $mychrs." ";

echo "
---Sort in ascending character order---
";
$num3=array('26','3');
sort($num3,SORT_STRING);
foreach ($num3 as $mychrs)
echo $mychrs." ";
?>

SORT_NUMERIC and SORT_STRING to declare ascending numerical or character order. If arranged in ascending order of numbers, it is: 3, 26; but if arranged in ascending order of characters, it is: 26, 3.

In addition to the ascending function, there is also a descending or reverse sorting function in PHP, which is the rsort() function, such as:

$num1=range(1,9);
rsort($num1); //here In fact, it is equivalent to range(9,1)

3. Sorting of associative arrays in PHP

PHP not only supports numerical index arrays, but also supports related arrays. For example, the following array is a related (associative) array:

$peoples=array('xm'=>'name','xb'=>'sex','mz'=>'nation','cs '=>'birth');

Using sort($peoples) defaults to sorting in ascending order of element definition values. In an associative array, you can use the asort() function to sort in ascending order of element values. The most important thing in an associative array is to sort by keywords (such as xm , xb, mz, etc.) in ascending order. This method uses the function ksort() function.

$peoples=array('xm'=>'name','xb'=>'sex','mz'=>'nation','cs'=>'birth ');
foreach ($peoples as $mychrs)
echo $mychrs." ";

echo "
--Sort in ascending order by element value--
";
asort( $peoples);
foreach ($peoples as $mychrs)
echo $mychrs." ";

echo "
--Sort in ascending order by keyword--
";
ksort ($peoples);
foreach ($peoples as $mychrs)
echo $mychrs." ";
?>
corresponds to the reverse sort rsort() descending function of the regular array with the sort() ascending function, and is associated Arrays also have corresponding descending functions: asort() function and arsort() function, ksort() function and krsort() function.
Memory: The prototype function is sort(), where a and k represent associative arrays that must be preceded, and reverse sorting is modified with r.

4, PHP array elements are randomly sorted

The shuffle() function is used in PHP to randomly reorder the array elements, and different sorting combinations will be displayed each time, such as:

$fer=array( 'cnbruce','cnrose','cnjames','cnanne');
shuffle($fer); //Randomly sorted every time the page is refreshed.

foreach ($fer as $mychrs)
echo $mychrs." ";
?>

5, PHP arrays are sorted in reverse order in the original order

You can use the array_reverse() function in PHP to sort the array elements in the original order Sort in reverse order. For example:

$fer=array('cnbruce','cnrose','cnjames','cnanne');
foreach ($fer as $mychrs)
echo $mychrs." ";

$fer=array_reverse($fer); //Sort the elements in the array in reverse order
echo "
--Reverse in original order--
";
foreach ( $fer as $mychrs)
echo $mychrs." ";
?>

output: cnbruce cnrose cnjames cnanne
--Reverse in original order--
cnanne cnjames cnrose cnbruce

Note here $fer=array_reverse ($fer); Any sorting function before this just declares a reference and does not redefine the original array, but when I debug the function, I need to redefine it. This is because array_reverse() returns a modified copy of the original array. If the original array is not needed, the original array can be redefined to overwrite it. Otherwise, another array must be defined to save the copy, for example: $fer_bak=array_reverse($fer_bak );


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP common functionsNext article:PHP common functions