PHP common functions - string
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

In today's era of rapid technological development, programming languages are springing up like mushrooms after a rain. One of the languages that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

"Go Language Development Essentials: 5 Popular Framework Recommendations" As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

Laravel is a popular PHP framework that is highly scalable and efficient. It provides many powerful tools and libraries that allow developers to quickly build high-quality web applications. Among them, LaravelEcho and Pusher are two very important tools through which WebSockets communication can be easily implemented. This article will detail how to use these two tools in Laravel applications. What are WebSockets? WebSockets

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

Detailed explanation of the role and usage of the echo keyword in PHP PHP is a widely used server-side scripting language, which is widely used in web development. The echo keyword is a method used to output content in PHP. This article will introduce in detail the function and use of the echo keyword. Function: The main function of the echo keyword is to output content to the browser. In web development, we need to dynamically present data to the front-end page. At this time, we can use the echo keyword to output the data to the page. e

The most popular Go frameworks at present are: Gin: lightweight, high-performance web framework, simple and easy to use. Echo: A fast, highly customizable web framework that provides high-performance routing and middleware. GorillaMux: A fast and flexible multiplexer that provides advanced routing configuration options. Fiber: A performance-optimized, high-performance web framework that handles high concurrent requests. Martini: A modular web framework with object-oriented design that provides a rich feature set.
