Home  >  Article  >  Backend Development  >  PHP common functions - string

PHP common functions - string

WBOY
WBOYOriginal
2016-07-29 08:50:411074browse

In the process of learning PHP, I compiled some commonly used functions. These are string functions.

header("Content-Type:text/html;charset=UTF-8");
//Remove both (unilateral) spaces or other predefined characters
$str = "##hello world@ @";
echo trim($str,'#,@')."
"; //hello world
echo ltrim($str,'#')."
" ; //hello world@@
echo rtrim($str,'@')."
"; //##hello world
/* chop() is an alias of rtrim()*/
/ /Return the directory part of the path
echo dirname("c:/testweb/home.php")."
"; //c:/testweb
/**String generation and conversion*/
// Fill the string into the specified string
$str = "hello world";
echo str_pad($str,20,'.',STR_PAD_BOTH)."
"; //.... hello world....
echo str_pad($str,20,'.',STR_PAD_LEFT)."
"; //....hello world
echo str_pad($ str,20,'.',STR_PAD_RIGHT)."
"; //hello world.........
//Reuse the specified string
echo str_repeat(".", 13)."
"; //.............
/* 13 is the number of repetitions*/
//Split the string into an array (including spaces , one space is 1 character)
$str = "my name is Junjun Liu";
$str1 = str_split($str,3);
print_r($str1); //Array ( [0] => my [1] => nam [2] => e i [3] => s J [4] => unj [5] => un [6] => Liu )
//Reverse the string
$str = "imagecreatetruecolor";
echo strrev($str)."
"; //roloceurtetaercegami
//Split the string according to the specified length
$ str = "An example on a long word is: Supercalifragulisticlasdkjflasdjfalsdkakd";
echo wordwrap($str,20, "
");
//Randomly scramble all the characters in the string (the numbers are scrambled The time interval symbols will also be shuffled)
$str = "a1,b2,c3";
echo str_shuffle($str)."
"; //1,ca32,b(random one kind)
//Parse the string into a variable
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first."
"; // value
echo $arr[0]."
"; // foo bar
echo $arr[1]."
"; // baz
print_r($ arr); //Array ( [0] => foo bar [1] => baz )
parse_str("id=23&name=John%20Adams",$myArray);
print_r($myArray); //Array ( [id] => 23 [name] => John Adams )
//Format numbers by thousandths group
echo number_format("1000000"); //1,000,000
echo number_format("1000000",2 ); //1,000,000.00
echo number_format("1000000",2,",","."); //1.000.000,00
//Case conversion
echo strtolower('NAME'); //name
echo strtoupper('name'); //NAME
echo ucfirst('my name is Junjun Liu'); //My name is Junjun Liu
echo ucwords('my name is Junjun Liu'); //My Name Is Junjun Liu
//html association tag
//Convert string to HTML entity
$str = "John & 'Adams'";
echo htmlentities($str, ENT_COMPAT); //John & 'Adams'
//Pre- Define character conversion to html encoding
htmlspecialchars($str);
echo "
";
//Replace n r and carriage return in the string with
tags to achieve newline output
$ string = "Thisrnisnranstringr";
echo nl2br($string);
/**
* This
* is
* a
* string
*/
//Strip HTML, XML, PHP tags
$str="asdasd< ;h3>woaini";
echo strip_tags($str); //asdasdwoaini
echo "
";
//Add a backslash before the specified character to escape the character in the string
$str = "Hello, My name is John Adams.";
echo addcslashes($str,'m'); //Hello, my name is John Adams
//Remove addcslashes backslashes
echo stripcslashes($str ); //Hello, my name is John Adams.
echo "


";
//Add a backslash before specifying the predefined characters
$str = "Who's John Adams?";
$str = addslashes($str);
echo $str; //Who's John Adams?
//Remove backslashes
echo stripslashes($str)."
"; //Who's John Adams?
// Add a backslash before some predefined characters in the string (all characters are escaped)
$str = "hello world.(can you hear me?)";
echo quotemeta($str)."< ;br/>"; //hello world.(can you hear me?)
//ASCII return character
echo chr(34); //Return "
//Return the ASCII code of the first character in the string Value
echo ord(abc); //97
echo "
";
/**String comparison*/
/*
* 1: The former is bigger
* -1: The latter is bigger
* 0: Equality before and after
*/
echo "Compare two strings without case sensitivity:".strcasecmp("abc","abd")."
"; //-1
echo "Compare two strings with case sensitivity:" .strcmp("abd","Abd")."
"; //1
echo "Compare two strings with case sensitivity:" .strncmp( "abcd","abcc",2)."
"; //0 /* 2 is the size of the first n strings compared*/
echo "Compare two strings without case sensitivity:". strncasecmp("abcd","abcc",4)."
"; //1
echo "Write and compare two strings in different sizes (in natural order):".strnatcmp("abc2"," abc12")."
"; //-1
echo "Write and compare two strings without distinguishing size (in natural order):".strnatcasecmp("Abc8","abc12")."< br/>"; //-1
/* String cutting and splicing*/
//Divide the string into small chunks (spaces also count)
$str="hello world hello world";
echo chunk_split($ str,2,"#"); //he#ll#o #wo#rl#d #he#ll#o #wo#rl#d#
//Cut the string
$first_token = strtok('/something ', '/');
$second_token = strtok('/');
var_dump($first_token); //string(9) "something"
var_dump($second_token); //bool(false)
// var_dump($first_token,$second_token);(Print two variables at the same time)
$str = "This is an /example string";
$tok = strtok($str,"/"); //This is an
echo $tok;
$str = "Thisisan /example string";
$tok = strtok($str,"/"); //Thisisan
echo $tok;
//Use one string to split another string for the logo
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
//Concatenate the array values ​​into a string using predetermined characters
$array = array('lastname', ' email', 'phone');
$a = implode(",", $array);
echo $a; // lastname,email,phone
//Intercept string
$str = "absadf";
echo substr($str,2,3); //sad
echo substr($str,-4,-1);//sad
/* String search and replacement*/
//String replacement operation, size sensitive Write str_replace (replaced font, replaced string, original string)
$str = "1,2,3:4,5:6";
echo str_replace(",",":",$str) ."
"; //1:2:3:4:5:6
echo str_replace(array(",",":"),";",$str)."
"; //1;2;3;4;5;6
echo str_replace(array(",",":"),array(";","#"),$str)."< ;br/>"; //1;2;3#4;5#6
//String replacement operation, case-insensitive
$str = "abcdefg";
echo str_ireplace("ABC","xyz ",$str); //xyzdefg
//Count the number of times a string appears in another string substr_count (search in this string, the searched string, the starting offset position, specify the offset Maximum position)
$str1 = "name";
$str2 = "my name isname name";
echo substr_count($str2,$str1); //2
//Replace a certain segment of the string with another string
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var
n"; //Original: ABCDEFGH:/MNRPQR/
/* These two examples use "bob" to replace the entire $ var. */
echo substr_replace($var, 'bob', 0) . "
n"; //bob
echo substr_replace($var, 'bob', 0, strlen($var)) . "
n"; //bob
/* Insert "bob" at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "
n"; //bobABCDEFGH:/MNRPQR/
/* The following two examples use "bob" to replace $var of "MNRPQR". */
echo substr_replace($var, 'bob', 10, -1) . "
n"; //ABCDEFGH:/bob/
echo substr_replace($var, 'bob', -7, -1) . "
n"; //ABCDEFGH:/bob/
/* Remove "MNRPQR" from $var.*/
echo substr_replace($var, '', 10, -1) . "
n"; //ABCDEFGH://
//Returns the similarity between two strings
$str1 = "abcdefgadfsa" ;
$str2 = "acdrgwsaasdf";
echo ((similar_text($str1,$str2)/strlen($str1))*100)."%"."
"; //58.333333333333%
//String search
$str = "zhangsan";
echo strstr($str,"a")."
"; //angsan starts from the front to find the position where a appears and intercepts it to the end ( Default false) Alias: strchr()
echo strstr($str,"a",true)."
"; //zh Start from the front to find the position where a appears and intercept it forward
echo strrchr( $str,"a")."
"; //an starts looking for a from the back and intercepts it to the end
echo strpos($str,"a")."
"; //2 Get the position where a appears for the first time in the string
echo strpos($str,"a",3)."
"; //6 Get the position where a appears in the string starting from position 3
echo strrpos($str,"a")."
"; //6 Get the position of the last occurrence of a in the string
//Convert the specified character
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans); //hello all, I said hi
echo strtr("baab", "ab ", "01"); //1001
$trans = array("ab" => "01");
echo strtr("baab", $trans); //ba01
/*
* strstr() : case sensitive
* stristr(): case insensitive
*/
/*
* strpos(): case sensitive
* stripos() case insensitive
* strrpos(): case sensitive
* strripos (): Case-insensitive
*
*/
//Returns the length of the first substring in the calculated string where all characters exist in the specified character set.
$var = strspn("42 is the answer to the 128th question.", "1234567890");
echo $var; //2 Because '42' is the first paragraph of subject and all characters exist in '1234567890' Continuous characters.
//Get the length of the starting substring of the unmatched mask
$a = strcspn('abcd', 'apple'); var_dump($a); //int(0)
$b = strcspn(' abcd', 'banana'); var_dump($a); //int(0)
$c = strcspn('hello', 'l'); var_dump($c); //int(2)
$d = strcspn('hello', 'world'); var_dump($d); //int(2)
/* String statistics*/
//Count the number of words contained in the string (third parameter??? ? ? ? ?
$str = "My name is John";
echo str_word_count($str); //4
print_r(str_word_count($str,1)); //Array ( [0] => My [1] => ; name [2] => is [3] => John )
print_r(str_word_count($str,2)); //Array ( [0] => My [3] => name [8] => is [11] => John )
//Count the length of the string
$str = ' ab cd ';
echo strlen($str); // 7
//Count the number of occurrences of all letters in the string ( 0,255), the number of occurrences of each character is represented by the corresponding ascii code value
$str = "aaaaasdfasdfwer;dlfgjjpoertuodbldbnlskjl;asfjoiwertowitwo";
echo "
";<br>//print_r(count_chars($ str));<br>echo "
";
//md5
$str = "hello4521";
echo md5($str); //5af267d811a324fd640b7ad2199dfe14
echo "
";
/ *
function getMd5($str){
return md5(md5($s)."tri");
}
*/
//md5_file()
$str = "ly.db";
echo md5_file($ str); //2f2b2262ed0732d497c90bf62af96240

The above has introduced the commonly used functions of PHP - strings, including PHP and string content. I hope it will be helpful to friends who are interested in PHP tutorials.

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