[introduction to PHP] beginners sort out the string functions commonly used in PHP, use summary and analysis (recommended)

PHP string operation

String is one of the important data types in PHP. In Web development, strings need to be processed and analyzed in many cases, which usually involves a series of operations, such as string formatting, string connection and segmentation, string comparison, search and so on. Therefore, it is very important for users to interact with the text system.

$str = "zhant";
// A string can be used as an array to access each character by subscript
echo $str[0]; // z
echo $str{2}; // a
// Modify string content
$str{4} = "g";
echo $str; // zhang

// A Chinese character takes up three bytes
$title = "Hello";
// strlen returns the length of the string
echo strlen($title); // 6
// Then when visiting, we need to splice
echo $title{0}.$title{1}.$title{2}; // you

Generate a random four digit verification code

// Generate a string consisting of A-Z and A-Z 0-9
$codes = implode("",range('a','z')).implode("",range('A','Z')).implode("",range(0,9));

$code = '';
for ($i=0; $i < 4; $i++) { 
	// Get random index number
	$index = mt_rand(0,strlen($codes)-1);
	$code .= $codes[$index];
}
echo "<span style='color:red'>{$code}<span>";

String comparison, segmentation and replacement

strcmp and strcasecmp string comparison functions

strcmp: https://www.php.net/manual/zh/function.strcmp.php

strcasecmp: https://www.php.net/manual/zh/function.strcasecmp.php

// If str1 is less than str2, the string comparison function returns < 0; If str1 is greater than str2, return > 0; If they are equal, return 0.
// StrCmp (string $STR1, string $STR2): int is strictly case sensitive  
echo strcmp('abc','ab'); // 1
echo strcmp('abc','abd'); // -1
echo strcmp('abc','ABC'); // 1
echo strcmp('abc','abc'); // 0
// Compare one by one according to ASCII code

// -------------------------------------
// strcasecmp is the same as the above return value, but is case insensitive
echo strcasecmp('abc','ABC'); // 0
echo strcasecmp('abc','abc'); // 0

Splitting and merging of strings

The value of implode() array is converted to string. join() is the alias of this function: implode()

Expand string to array: https://www.php.net/manual/zh/function.explode.php

list() assigns the values in the array to a group of variables: https://www.php.net/manual/zh/function.list.php

$study = ['html','css','js','es6','jquery','vue','react'];
// The first parameter of the array to string function is the separator, and the second parameter is the array
echo implode('---',$study);
// html---css---js---es6---jquery---vue---react
echo join(',',$study);
// html,css,js,es6,jquery,vue,react

// Convert expand string to array
$str = "html,css,js,es6,jquery,vue,react";
// What is used to split strings
print_r(explode(",", $str));
/*
Array ( [0] => html [1] => css [2] => js [3] => es6 [4] => jquery [5] => vue [6] => react )
 */
// The third parameter specifies to split into several arrays
print_r(explode(",", $str,6));
/*
Array ( [0] => html [1] => css [2] => js [3] => es6 [4] => jquery [5] => vue,react )
 */


// -------------------------
// list() assigns the value of the array to several variables
list($localhost,$username,$password,,$port) = explode(":", 'localhost:root:root:utf8:3306');
echo "mysql:host={$localhost};username={$username};password={$password};port={$port}";
/* mysql:host=localhost;username=root;password=root;port=3306 */
// The assignment of associative arrays to variables should be one-to-one in the form of key value pairs
$params = ['host'=>'localhost','username'=>'root','password'=>'root'];
list('host'=>$host,'username'=>$username,'password'=>$password) = $params;
printf("host=%s;username=%s;password=%s",$host,$username,$password);
/* host=localhost;username=root;password=root */

String interception

// substr() string interception function 
echo substr('abcdefg',3,2); // de
echo substr('abcdefg',3); // defg
echo substr('abcdefg',-3); // efg

// The ASCII conversion function chr() ord() is generally used to determine whether the user name starts with a letter, intercept the first character to determine its ASCII size range A 65 a 97
// ASCII comparison table http://c.biancheng.net/c/ascii/
// ucfirst converts initials to uppercase
// ord() string to ASCII
// chr() ASCII to character
$username = 'admin';
echo ord(substr(ucfirst($username),0,1))>=65 && ord(substr(ucfirst($username),0,1))<=90?'The user name is correct':'Please start the user name with a letter';
echo strlen($username)<4||strlen($username)>10?'The length of user name should be 6-10 Characters':'The user name is correct';

String replacement function (sensitive word escape)

str_replace() substring replacement: https://www.php.net/manual/zh/function.str-replace.php

// Replace the directory separator of the window system with the Linux directory separator
$path = "D:\phpstudy_pro\Extensions\php\php7.3.9nts\php.exe";
// View path separators supported by the current operating system
echo DIRECTORY_SEPARATOR; 
// Character content to be replaced character content string after replacement  
echo str_replace('\\','/',$path);
/* D:/phpstudy_pro/Extensions/php/php7.3.9nts/php.exe */

// The fourth parameter is the number of times the replacement can be received
echo str_replace('transfer accounts','***','Support WeChat large transfer, Alipay transfer, bank card transfer.',$count);
// Support for WeChat's large scale * * *, Alipay * * *, bank card * * *
echo "\'transfer accounts\'Occurrence times of sensitive words:{$count}";

// The character content of the first parameter to be replaced can be an array
$vowels = array("gambling","beauty",'Licensing','Macao');
echo str_replace($vowels, "**", "Welcome to the gambling platform, Macao crown gambling website,Beauty online licensing");
// Welcome to * * platform, * * crown * * website, * * Online**

// Both sensitive words and replacement contents can be arrays, which will be replaced with corresponding contents
$search = ['make friends','advertisement','transfer accounts','live broadcast','commerce','Chat with','opposite sex'];
$flag = ['***','---','&&&','000','*goods*','chat','Same sex'];
$news = 'The company undertakes all kinds of advertising agents, provides live broadcast and cargo teaching services, and provides online chat services for heterosexual friends';
echo str_replace($search,$flag,$news);
/* The company undertakes various --- agents, provides 000 and * goods * teaching services, and provides same-sex * * * online chat services */

URL link parsing function

parse_str() parses strings into arrays

https://www.php.net/manual/zh/function.parse-str.php

parse_url() parses the URL and returns an array of its components

https://www.php.net/manual/zh/function.parse-url.php

http_build_query generate URL_ Request string after encode

https://www.php.net/manual/zh/function.http-build-query.php

// parse_str() parses strings into arrays
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
extract($output);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
$url = "id=1&name=zhang&gender=1";
parse_str($url,$result);
echo "<pre>";
print_r($result);
/*
Array
(
    [id] => 1
    [name] => zhang
    [gender] => 1
)
*/

// --------------------------------
// parse_url() parses the URL and returns an array of its components
$url = 'http://zhang.com:password@hostname/0425/demo.php?id=1&name=zhang#anchor';
echo "<pre>";
print_r(parse_url($url));
/*
Array
(
    [scheme] => http
    [host] => hostname
    [user] => zhang.com
    [pass] => password
    [path] => /0425/demo.php
    [query] => id=1&name=zhang
    [fragment] => anchor
)
 */
// You can return the required part by setting the second parameter
echo parse_url($url,PHP_URL_QUERY); // id=1&name=zhang
echo parse_url($url, PHP_URL_PATH); // /0425/demo.php

// -------------------------------------------
// http_build_query - request string after generating URL encode
$url = "http://zhang.com?name = Zhang Shan & age = 20 & email= zhang@qq.com ";
$query = parse_url($url,PHP_URL_QUERY);
// name = Zhang Shan & age = 20 & email= zhang@qq.com
// Get query through parse_str to array
parse_str($query,$params);
echo "<pre>";
print_r($params);
/*
Array
(
    [name] => Zhang Shan
    [age] => 20
    [email] => zhang@qq.com
)
 */
// Request parameter to Unicode
echo http_build_query($params);
// name=%E5%BC%A0%E7%8F%8A&age=20&email=zhang%40qq.com
// http_ build_ The query parameter can be not only an array, but also an object
echo http_build_query(new class{
    public $name = 'admin';
    public $email = 'admin@php.cn';
    private $gender = 'male'; // Private member
});
// name=admin&email=admin%40php.cn

Convert normal picture to bs64 picture

Output a picture in html

<img src='https://c-ssl. duitang. com/uploads/item/202006/20/20200620205947_ kxnPk. thumb. 1000_ 0. JPEG 'ALT =' beauty 'width = "300" > 

Disguise PHP script as image image

// Camouflage request header response
header('content-type:image/jpg');
// Open file
$file = file_get_contents('https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg');
echo $file;
// Because the response header is set, the current script can only parse the picture. In the html tag, you can link the file path to display the picture content

This allows you to link the script to display images in html via img tags

<img src="http://zhang.com/0430/demo.php" width="300">

base64 encode the picture

base64_encode(): use MIME base64 to encode data

https://www.php.net/manual/zh/function.base64-encode.php

base64_decode(): decode the data encoded by MIME base64

https://www.php.net/manual/zh/function.base64-decode.php

<?php
    $str = 'This is an encoded string';
	echo base64_encode($str); // Encoded string data	
	// VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

    $file = file_get_contents('https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg');
    $imgbs64 = base64_encode($file);
	echo $imgbs64; // Output 60 bit hash value
?>
// Display bs64 bit pictures through img tag
<img src="data:image/jpeg;base64,<?=$imgbs64 ?>" width="300">

In the figure, we can see that the picture links processed by bs64 encoding are super long, and users cannot obtain the real links of the pictures

String hash processing

md5() returns a 32-bit hash value

https://www.php.net/manual/zh/function.md5.php

sha1() returns a 40 bit hash value

https://www.php.net/manual/zh/function.sha1.php

Since the algorithm that the above function depends on is not complex enough, it is not recommended to encrypt plaintext password

password_hash - create hash of password (recommended)

password_verify - verify that the password matches the hash value

// Since md5() and sha1() are organic, we can add salt to them
$salt = 'zhangshuai';
echo sha1('root'.$salt);
// 43f5582e40049d275977f9ed76c8972723e9b4b5

// --------------------------------------------

// password_hash create hash of password
$pwd = password_hash('zhang',PASSWORD_DEFAULT);
echo $pwd;  // Returns a 60 character string
// password_verify - verify that the password matches the hash value
echo password_verify('zhang',$pwd)?'The password is correct':'Password error';

// ------------------------------------------

// md5_file() hashes the file
// Generate md5 to store in file
$file_md5 = md5_file('demo.php');
file_put_contents('md5file.txt',$file_md5);
// Verify in another PHP file when demo When PHP is modified, it cannot match md5 stored in the file
if(md5_file('demo.php') === file_get_contents('md5file.txt')){
    echo "The file is secure and has not been tampered with maliciously";
}else{
    echo "Warning! The file has been tampered with";
}

More string related functions

  1. String lookup

stripos() is used to find the first occurrence of a part of a string (case insensitive)

strripos() is used to calculate the position of the last occurrence of the specified string in the target string (case insensitive)

strpos() is used to find the first occurrence of a string

strrpos() is used to find the position of the last occurrence in the string

var_export(stripos('xyz', 'c'));; // If not found, false will be returned
echo stripos('ABCabc', 'c'); // Return to first occurrence position 2

echo strripos('ABCabcd', 'c'); // Last occurrence position 5

echo strpos('ABCabc','c'); // 5 case sensitive
echo strpos('ABCabc','C'); // 2

echo strrpos('ABCcabcAb','c'); // 6 
  1. Case conversion of strtoupper and strtower strings
  2. str_ireplace() and str_replace() string replacement
  3. substr() and mb_substr(): intercept string
  4. trim(): remove spaces on both sides of the string
  5. Strlen () and mb_strlen(): get string length
  6. addslashes() and stripsplashes(): String escape and restore
  7. str_repeat(): repeat a string
  8. str_shuffle(): randomly shuffle strings

Answers to PHP test questions

1-5: C ABD D C A

6-10: AD D B C A

11-15: A B ACD D A

16-20: B A D A B

21-23: C B C

Job content: complete a user registration page and verify the form fields with the string function library summarized in xmind file? For example, limit the length of the password, the two passwords must be consistent, the verification code must be verified, and the first letter of the user name must be a letter, etc?

<!-- User registration page register.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User registration page</title>
    <link rel="stylesheet" type="text/css" href="css/regist.css">
</head>
<body>
    <div class="wrapper">
        <article>
            <h1><span>Personal blog registration</span></h1>
            <div class="main">
                <form action="" method="post"╬┐nsubmit="return false">
                    <div class="tel">
                        <input type="email" name="email" placeholder="Please enter the mailbox" id="telephone" required >
                    </div>
                    <div class="userName">
                        <input type="text" name="userName" placeholder="enter one user name" id="username" required>
                    </div>
                    <div class="password">
                        <input type="password" name="pwd" placeholder="Please input a password" id="pwd" required>
                    </div>
                    <div class="againpwd">
                        <input type="password" name="cpwd" placeholder="Please enter the password again" id="cmpwd" required>
                    </div>
                    <div class="captcha">
                         <input type="text" name="captcha" id="captcha" placeholder="Please enter the verification code" required>
                        <img width="60" height="37" onclick="this.src='gd_captcha.php?'+new Date().getTime();" style="margin: 10px auto;vertical-align: bottom;" src="gd_captcha.php">
                        <em id="captchainfo">Prompt message</em>
                    </div>
                    <button>register</button>
                </form>
            </div>
        </article>       
    </div>
    <script type="text/javascript" src="js/reg.js"></script>
</body>
</html>
/* Login page style register css */
*{ margin: 0;padding: 0;font-family: Microsoft YaHei;}
em{display: block;font-style: normal;font-size: 14px;color:red}
li{list-style: none;display: inline-block;}
li a{text-decoration: none;}
html,body,.wrapper{
	width: 100%;
	height: 100%;
	overflow: hidden;
}
.wrapper{
	background: url(http://zhsh520.com/hero-bg.jpg);
	background-size: 100% 100%;
	position: relative;
}
article{
	width: 1200px;
	margin: 0 auto;
}
article{
	width: 400px;
	margin: 100px auto 0px auto;	
}
article h1{width: 400px;color: #fff;text-align: center;margin-bottom: 15px;font-weight: normal;}
article h1 em{display: inline-block;color:#5593ce;font-size: 25px;}
.main{
	padding: 40px 0px;
	width: 100%;
	background-color: rgba(0, 0, 0, 0.6);
}
form{
	width: 297px;
	margin: 0 auto;
}
.main form input{
	margin: 10px 0;
    width: 280px;
    height: 35px;
    border-radius: 3px;
    display: inline-block;
    border: 1px solid rgb(165, 161, 161);
    padding-left: 10px;
}
.main form input[name="captcha"]{
	width: 200px;
}
form button{width: 290px;height: 35px;background-color: red;color: #fff;border:none;margin-top: 15px;letter-spacing: 10px;font-size: 16px;text-align: center;}
footer{
	width: 100%;
	position: absolute;
	left: 0;
	bottom: 50px;
	font-size: 14px;
	color: #5593ce;
}
footer ul{width: 570px;height: 35px;}
footer p{width: 100%;text-align: center;}
footer ul li{display: inline-block;width: 90px;height: 13px;line-height: 13px;border-right: 1px solid #5593ce;text-align: center; }
footer ul li a{font-size: 14px;color:#5593ce; }
footer ul,footer p{margin: 0 auto;}
// Submit information validation reg js 
document.querySelector('button').addEventListener("click",function(e){
	const formdata = new FormData(document.querySelector('form'));
	const xhr = new XMLHttpRequest();
    xhr.open("post", "regist_check.php");
    xhr.onload = () => {
    	let json = JSON.parse(xhr.response);
    	if(json.status==0){
            document.querySelector("#captchainfo").textContent = json.msg;
            document.querySelector("#captchainfo").style.color = "red";
            
        }else{
            document.querySelector("#captchainfo").textContent = json.msg;
            document.querySelector("#captchainfo").style.color = "green";
            setTimeout(()=>{
                window.location.href = "http://baidu.com";
            },2000)
        }
    };
    xhr.send(formdata);
});

document.querySelector('#captcha').addEventListener('blur',function(e){
	// console.log(e.target.value);
	const xhr = new XMLHttpRequest();
    xhr.open("post", "captcha_check.php");
    xhr.onload = () => {
    	let json = JSON.parse(xhr.response);
    	if(json.status==0){
    		document.querySelector("#captchainfo").textContent = json.msg;
            document.querySelector("#captchainfo").style.color = "red";
    		e.target.focus();
    	}else{
    		document.querySelector("#captchainfo").textContent = json.msg;
            document.querySelector("#captchainfo").style.color = "green"
    	}
    };
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send("captcha="+e.target.value);
})
// User information verification register_ check. php
<?php  
session_start();
$user = $_POST;
if(strlen($user['userName'])<4 || !preg_match("/^[A-Za-z]/i",$user['userName']) ){
	echo json_encode(['status'=>0,'msg'=>'The user name must be no less than four digits long and start with a letter']);
}else if(strcmp($user['pwd'],$user['cpwd'])!== 0){
	echo json_encode(['status'=>0,'msg'=>'The two passwords are inconsistent']);
}else if(strcasecmp($_SESSION["captcha"],$user["captcha"])!== 0){
	echo json_encode(['status'=>0,'msg'=>'Incorrect verification code']);
}else{
	echo json_encode(['status'=>1,'msg'=>'Registration succeeded, please wait']);
}
?>
// Captcha of verification code_ check. php
<?php  
/**
 * Accept the verification code submitted by the user when logging in
 */
session_start();
//1. Obtain the verification code submitted by the user
$captcha = $_POST["captcha"];
 
//2. Check the verification code in the session with the verification code submitted by the user. When successful, prompt that the verification code is correct, and destroy the previous session value. If unsuccessful, resubmit
if(!empty($captcha) && strtolower($_SESSION["captcha"]) === strtolower($captcha)){
    echo json_encode(['status'=>1,'msg'=>'The verification code is correct']);
}else{
    echo json_encode(['status'=>0,'msg'=>'Incorrect verification code']);
}
// Verification code generation gd_captcha.php
<?php
session_start();
$image = imagecreatetruecolor(100, 30);
 
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);
$content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$captcha = "";
for ($i = 0; $i < 4; $i++) {
    // font size
    $fontsize = 10;   
    // Font color
    $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
    // Set font content
    $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
    $captcha .= $fontcontent;
    // Displayed coordinates
    $x = ($i * 100 / 4) + mt_rand(5, 10);
    $y = mt_rand(5, 10);
    // Fill content into canvas
    imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
$_SESSION["captcha"] = $captcha;
 
//4.3 setting background interference elements
for ($$i = 0; $i < 200; $i++) {
    $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
    imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
}
 
//4.4 setting interference line
for ($i = 0; $i < 3; $i++) {
    $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
    imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
}
 
//5. Output picture header information to the browser
header('content-type:image/png');
 
//6. Output pictures to browser
imagepng($image);
 

Browse address: http://easys.ltd/regist/regist.html

Display effect:

Keywords: PHP

Added by stolzyboy on Fri, 18 Feb 2022 06:40:10 +0200