Learning courses are derived from:
Introduction to PHP string manipulation
PHP Manual (Simplified Chinese) Link on PHP Official Website
Declaration string
A string is a scalar and requires delimiters
According to the declaration delimiter, it can be divided into:
1. Single quotation mark:''
2. Double quotation marks: ""
3. Herdoc grammatical structure
4. Nodoc grammatical structure
Special symbols: rn,t,$
Single quotation mark
- Ordinary strings can be declared
- Can only escape single quotation marks and backslashes
- Unresolvable variables
<?php echo 'www.php.cn'; echo '<hr/>'; echo 'I \'m a teacher';//A single quotation mark appears in a string in a single quotation mark and needs to be escaped echo '<hr/>'; echo 'I like it php Chinese Network\r\n'; echo '<hr/>'; //If you point to the output backslash, you do not need to escape echo 'C:\temp\\hello.php';//Conversion of the backslash itself $name = 'peter'; echo '$name';//Unresolvable variables echo '<hr/>';
Double quotation marks
- Declare a common string
- Escape all special characters
- Variable Analysis
echo "php Chinese Network"; echo '<hr/>'; // If a double quotation mark appears in a string, it needs to be escaped echo "php Chinese Network\"www.php.cn\""; echo '<hr/>'; // Special characters in double quotation marks are parsed echo "C:\php\demo.php"; echo '<hr/>'; echo "C:\temp\php\demo.php"; echo '<hr/>'; $name = 'peter'; echo "My name is: $name";
Differences and Relations between Herdoc and Nodoc Grammatical Structures
1. New lines, spaces will be reserved
2. Because there is no need to escape quotation marks, it is suitable to output large chunks of HTML code.
3. Variables can be parsed automatically and are suitable for template output.
4. If heredoc or nowdoc is spliced with other strings, no semicolon is added at the end.
<?php // heredoc grammatical structure (double quotation marks) $name = 'php Chinese Network'; echo "www.php.cn \"Peter zhu\" $name \r\n"; echo '<hr/>'; echo <<<"EOA" www.php.cn "Peter zhu" $name \r\n EOA; echo '<hr/>'; // nowdoc grammatical structure (single quotation mark) // Suitable for output of large chunks of HTML text echo 'www.php.cn \'php Chinese Network\''; echo '<hr/>'; echo <<< 'EOD' www.php.cn 'php Chinese Network' <hr/> <form action="index.php" method="get"> //User name: <input type='text'> </form> EOD; ?>
Local variables and class attributes initialized by heredoc and nowdoc
<?php // Initialization of function variables and class attributes with heredoc and nowdoc function welcome($lang='PHP') { $study = <<<"STU" //My favorite programming language is: $lang STU; static $hello = <<<"EOD" //Welcome to the Chinese PHP website "www.php.cn"rn <hr/>. EOD; return $hello.$study; } echo welcome('JAVA'); echo '<hr color="red"/>'; class Student { public $name = 'Peter zhu'; public static $alias = <<<"NAME" //My name is Peter Zhu < hr/>. NAME; const COUNTRY = <<< COUN //I love my country. How about you? COUN; } echo (new Student)->name;echo '<hr/>'; echo Student::$alias; echo '<hr/>'; echo Student::COUNTRY; echo '<hr/>'; ?>
Two Grammars of Variable Resolution
<?php $siteName = 'php Chinese Network'; $books = ['course'=>'php', 'java', 'python']; echo "The name of the website is: $siteName"; echo '<hr/>'; // echo: "My course is $books[0]"; // echo: "My course is $books['course']"; echo "My course is {$books['course']}"; echo '<hr/>'; class Web { public $webSite = 'php Chinese Network'; public static $domain = 'domain'; const APP = 'app'; } $domain = 'www.php.cn'; $app = 'My application'; echo (new Web)->webSite;echo '<hr/>'; echo Web::$domain; //General method echo '<hr/>'; echo "${Web::$domain}";//Indirect method echo '<hr/>'; echo "${Web::APP}";
Addition, deletion and modification of strings
<?php // Addition, deletion and modification of strings: treat strings as an array $domain = 'http://www.php.cn'; //query echo $domain[3];echo '<hr/>'; echo $domain[3];echo '<hr/>'; //Newly added echo 'The length of the string is'.strlen($domain);echo '<hr/>'; echo $domain; $domain{17} = '/';echo '<hr/>'; echo $domain; //To update $domain{17} = '?'; echo '<hr/>'; echo $domain; //delete // String deletion is only a visual effect, in which the real character is not deleted, but replaced by an empty string. $domain[3] = ' '; echo '<hr/>'; echo $domain; echo '<hr/>'; echo 'The length of the string is'.strlen($domain);echo '<hr/>'; ?>
Substring processing substr and related functions
<?php // 1.substr(string, start,length): Get the contents of the substring $email = 'peter@qq.com'; echo substr($email, 0, 5), '<hr/>'; echo substr($email, -3, 3), '<hr/>';//Negative Three Begins to Get Three //2. Substitution string: substr_replace() echo substr_replace($email, 'php', 6, 2), '<hr/>'; // Setting the length of substring to 0 to realize insertion without deletion echo substr_replace($email, '_zhu', 5, 0), '<hr/>'; // Setting up empty substring to realize insertion deletion echo substr_replace($email, '', 6, 2), '<hr/>'; // Insert characters in their real position echo substr_replace($email, 'My mailbox number:', 0, 0), '<hr/>'; // 3.substr_count(): Frequency (number) of query substrings $str = 'php The domain name of the Chinese Internet is www.php.cn,It is the largest in China. php Online Learning Platform'; echo substr_count($str,'php'),'<hr/>';//3 echo substr_count($str,'php',0,20),'<hr/>';//Designated Scope 1 //4.substr_compare($str,$str1) comparison substring // 0: Equal < 0, the first substring is smaller than the second, and if it is greater than 0, the first substring is larger than the second substring. echo substr_compare('www.php.cn', 'www.php.cn', 0),'<hr/>'; echo substr_compare('www.php.cn', 'php.cn', 4),'<hr/>'; // It should be noted that the search starting position specified here starts with the first number. ?>
String retrieval functions strpos() and strstr()
<?php /* strpos():Get the location of the substring, the substring search function, and find the index according to the content */ $domain = 'www.php.cn'; echo strpos($domain,'php',0),'<hr/>';//4 echo strpos($domain,'p',5),'<hr/>';//'5'Find the starting position $siteName = 'php Chinese Network'; // A Chinese character takes up three bytes echo strpos($siteName,'in'),'<hr/>'; echo strpos($siteName,'writing'),'<hr/>'; // Open mbString using multibyte security function mb_. echo mb_strpos($siteName,'writing'),'<hr/>'; // strstr() echo strstr($domain,'p').'<hr/>';//Output the current results and subsequent strings echo strstr($domain,'p',true).'<hr/>'; echo strstr($domain,'p',true).strstr($domain,'p'); ?>
Fill and replace str_pad() and str_replace() strings
String padding str_pad()
string str_pad( string $input, int $pad_length[, string $pad_string = " "[, int $pad_type = STR_PAD_RIGHT]] )
This function returns the result that the input is filled from the left, right or both ends to the specified length. If the optional pad_string parameter is not specified, input will be filled with space characters, otherwise it will be filled with pad_string to the specified length.
$input = 'php.cn'; //The second parameter indicates how long the string will be filled in. echo str_pad($input,10),'<hr/>'; echo str_pad($input,10,' ',STR_PAD_RIGHT),'<hr/>'; echo str_pad($input,10,'*',STR_PAD_LEFT),'<hr/>'; echo str_pad($input,10,'#',STR_PAD_BOTH),'<hr/>';
str_repeat() character repeat function
echo str_repeat('*', 20).'<hr/>';
str_shuffle() Random Disturbance Function
echo str_shuffle($input).'<hr/>';
str_replace() string replacement function
$email = 'peter@qq.com'; str_replace('qq', '163', $email).'<hr/>'; $hobby = 'My favorite fruits are apples, bananas and peaches.'; $fruits1 = ['Apple','Banana','Peach']; $fruits2 = ['watermelon','Pear','Orange']; echo $hobby.'<hr/>'; echo str_replace($fruits1,$fruits2,$hobby);echo '<hr/>'; echo str_replace('/', '\\', 'C://demo/index.php');
String length statistics strlen(), mb_strlen(), mab_strwidth()
<?php // strlen() $siteName = 'php Chinese Network'; echo strlen($siteName).'<hr/>'; // utf8,3 bytes represent one Chinese echo mb_strlen($siteName).'<hr/>'; // Processing all bytes of text by 2 bytes echo mb_strwidth($siteName).'<hr/>'; ?>
String segmentation and combination explode(), implode()
<?php // Segmentation and Combination of Strings $path = 'C://www/blog/case/index.php'; echo '<pre>'; print_r(explode('/',$path)); echo '</pre>'; $fruits = 'Apple,Orange,Pear,Watermelon'; echo '<pre>'; print_r(explode(',', $fruits)); echo '</pre>'; // implode() splices arrays into strings $city = implode('---', ['Hefei','Wuhu','Anqing','Lu'an']); if (is_string($city)) { echo 'Character string:'.$city; } else { echo 'Not a string'; } ?>
String type conversion (temporary, permanent, automatic)
Character type conversion echo 300,'<hr/>'; //String representation of numeric types echo true,'<hr/>'; //true to character'1' echo false,'<hr/>'; //false to'' echo range(1,5); //Array var_dump(range(1,5)); echo '<hr/>'; echo (new stdClass); var_dump(new stdClass); //Objects cannot be converted directly to character output unless _toString() echo fopen('lesson05.php','r'); //Resource id #3
// There are three types of conversion: mandatory conversion, permanent conversion, and automatic conversion. //1. Forced Conversion, Temporary Conversion echo gettype((string)500),'--',gettype(500),'<hr/>'; echo gettype(strval(500)),'--',gettype(500),'<hr/>'; echo gettype(strval(true)),'--',gettype(true),'<hr/>'; // 2. Permanent conversion settype($val,$type) $old = 500; $current = gettype(settype($old, 'string')); echo gettype($current).'---'.gettype($old); echo '<hr color="red"/>'; //3. Auto-conversion, context-related echo 150+'35abc','<hr/>'; //'35abc'==>35 echo 150+'a35bc','<hr/>'; //'a35bc'==>0 echo 150+true,'<hr/>'; //true ==>1 echo 150+false,'<hr/>'; //false==>0 echo 150+null,'<hr/>'; //null==>0
Formatting functions of strings
<?php // toggle case echo strtolower('HTTP://WWW.PHP.CN'),'<hr/>'; echo strtoupper('http://www.php.cn'),'<hr/>'; // String Rotation Timestamp date_default_timezone_set('PRC');//Setting default time zone echo strtotime('2017-10-10'),'<hr/>'; echo date('Y-m-d',1507564800),'<hr/>'; // 1000-bit separator, 1,234,567,894 echo number_format(1234567890),'<hr/>'; // Set up decimal digits echo number_format(123456789.556,2),'<hr/>'; // Custom decimal point and kilobit character echo number_format(123456789.556,2,'*','#'),'<hr/>'; // Conversion between ACSII codes and integers // Converting integers to ASCII codes echo chr(88),'<hr/>';//Recommended Writing echo chr(88),'<hr/>'; // Converting ASCII codes to integers echo ord('X'),'<hr/>'; //The n newline character of the string is converted to <br/> in html echo "php Chinese Network \n www.php.cn",'<hr/>'; echo nl2br("php Chinese Network \n www.php.cn"),'<hr/>'; // Coding Conversion echo iconv('utf-8', 'gbk', 'php Chinese Network').'<hr/>'; // Encryption function echo md5(md5(123456)),'<hr/>'; echo sha1(123456),'<hr/>'; ?>
String Content Filtering and Transcoding
<?php // String Content Filtering and Transcoding // trim() function $str = " www.php.cn "; echo '<pre>'; echo $str;echo '<hr/>'; echo trim($str),'<hr/>';//Remove the blanks on both sides echo ltrim($str),'<hr/>';//Remove the space on the left echo rtrim($str),'<hr/>';//Remove the space on the right echo '</pre>'; // Filter special characters that need to be escapedrnt0 $str = " \r\0 www.php.cn \n\t "; echo $str;echo '<hr/>'; echo trim($str),'<hr/>';//Remove the special characters on both sides $str = "www.php.cn"; echo $str,'<hr/>'; echo trim($str,'.cn'),'<hr/>'; // strip_tags() filters out html tags $code = <<<"CODE" <h3 style="color:red">$str</h3> <p style="color:blue">php Chinese Network</p> CODE; echo $code,'<hr/>'; echo strip_tags($code),'<hr/>'; echo strip_tags($code,'<h3>'),'<hr/>'; // htmlspecialchars(string) converts special characters to html entities // Special Characters: html code has special meaning: <,>, &,', mainly these five // Entity characters: <: & lt; > gt; &: & amp; "& quot;':& apos; $html = <<< "HTML" <h3 style="color:green">PHP The best language in the world</h3> <p style="color:blue"> There is no language at all. PHP good</p> HTML; echo $html,'<hr/>'; echo htmlspecialchars($html),'<hr/>'; $code = htmlspecialchars($html); // Transcoding and Output of Coded Data echo htmlspecialchars_decode($code); ?>
Serialization of Strings and json Processing
<?php // json is the object representation of JavaScript // json_encode() Converts an array or object to a string in json format $arr = ['id'=>10,'name'=>'peter','isMarried'=>true]; $obj = new stdClass; $obj->name = 'Miss Zhu'; $obj->salary = 3000; // Convert arrays to json format echo json_encode($arr),'<hr/>'; // Converting objects to json format echo json_encode($obj),'<hr/>'; // json_decode: Converts a json-formatted string to a PHP object, not an array $json = '[ {"id":10,"name":"peter","grade":90}, {"id":18,"name":"zhu","grade":80}, {"id":21,"name":"wang","grade":70} ]'; // Converting json strings to PHP objects $jsonObj = json_decode($json); echo '<pre>'; print_r($jsonObj); echo '</pre>'; echo 'My name is:'.$jsonObj[1]->name,'<hr/>'; // Serialization of strings: Save the structure and type of arrays to variables or files for easy storage or transmission $user = ['id'=>1,'username'=>'admin','passward'=>md5(123456)]; echo '<pre>'; print_r($user); $admin = serialize($user); echo $admin; // a:3:{s:2:"id";i:1;s:8:"username";s:5:"admin";s:8:"passward";s:32:"e10adc3949ba59abbe56e057f20f883e";} // Type: Length: Value echo '</pre>'; echo '<hr/>'; // Deserialize $temp = unserialize($admin); print_r($temp); ?>