search
HomeBackend DevelopmentPHP TutorialPHP string operation introductory tutorial_PHP tutorial

PHP string operation introductory tutorial_PHP tutorial

Jul 21, 2016 pm 03:59 PM
phpGetting Started TutorialBasestringoperateyesSimplelanguageimportant

Regardless of the language, string manipulation is an important foundation, often simple and important. Just like human speech, it generally has a form (graphical interface) and language (print string?). Obviously strings can explain more things. PHP provides a large number of string operation functions, which are powerful and relatively simple to use. For details, please refer to http://cn2.php.net/manual/zh/ref.strings.php. The following will briefly describe its functions and characteristic.

Weakly typed

PHP is a weakly typed language, so other types of data can generally be directly applied to string operation functions and automatically converted into string types for processing, such as:


echo substr("1234567", 1, 3);
and
echo substr(123456,1, 3);
are the same


Definition

Generally use double quotes or single quotes to identify a string. For example,


$str = "i love u";
$str = 'i love u';

There are some differences between the two. The latter treats all single quotation marks as characters; the former does not. For example


$test = "iwind";
$str = "i love $test";
$str1 = 'i love $test';
echo $str; //Will get i love iwind
echo $str1; //Will get i love $test

The same behavior of the following two examples is also different:


echo "i love test"; // will get i love est, t has been regarded as escape
echo 'i love test'; // will get i love test

so it can be simply considered a double The content in quotation marks is "interpreted", and the content in single quotation marks is "what you see is what you get" (in particular, '' will be recognized as a ''). Obviously, the double quotation mark form is more flexible. Of course, single quotation marks will be suitable for some special occasions, which will not be explained here.

Output

The most commonly used output in PHP is echo and print. Both are not real functions, but language constructs, so there is no need to use double brackets when calling (such as


echo("test");print("test")). Both can be assigned values ​​when outputting:
echo $str="test"; //On the one hand, test is output, On the one hand, assign "test" to the string variable $str
print $str="test";

In addition to the different names, there are other differences between the two. Print has a return value and always returns 1, but echo does not, so echo is faster than print:


$return = print "test";
echo $return; // Output 1

For this reason, print can be used in compound statements, but echo cannot:


isset($str) or print "str variable is undefined"; // Will output "str variable is not defined"
isset($str) or echo "str variable is not defined";// Will prompt analysis error



echo can output multiple strings at a time. Print is not possible:
echo "i ","love ","iwind"; // will output "i love iwind"
print "i ","love ","iwind"; // will Prompt error


echo, print can also output a string called "document syntax", with syntax such as:
echo ...
String content
...
Tag name;
For example


echo i love iwind
test;

It should be noted that the two label names at the beginning and end of the statement are the same, and there must be no blank space before the latter label name, that is, it must be written in a square format. The content of the document syntax output identifies variable names and common symbols, which is roughly the same as the function of double quotes.

In addition to outputting echo and print, PHP also provides some functions for formatting strings, such as printf, sprintf, vprintf, vsprintf, which will not be explained in detail here.
Connection

Use the "." operator to connect two or more strings to form a new string in the order of the strings.


$str = "i " . "love " . "iwind";
$str here is "i love iwind"; string. Of course, you can also use the .= operator:
$str = ""; // Initialization
$str .= "i love iwind";

Initialization is used here because it is not defined The variable will generate a notice error when used, "" or null can simply represent an empty string.

Length

PHP provides the strlen function to calculate the length of a string:


$str = "test";
echo strlen($str); // Will output 4

What is a little strange is that strlen treats Chinese, Japanese and other Chinese characters and full-width characters as two or four lengths. Fortunately, the two functions mbstring or icon can help solve this problem, such as:


$len = iconv_strlen($str, "GBK");
$len = mb_strlen($str, " GBK");

Note: The mbstring module provides a large number of processing functions for strings containing multi-byte characters. It is recommended to apply more. Since this article is about getting started with strings, I will not go into details. Commentary.

Separation and concatenation

PHP allows you to separate a string into an array according to a delimiter, or combine an array into a string. Look at the following example:


$str = "i love iwind";
$array = explode(" ", $str);

The above explode function is Separate the $str string by space characters, and the result returns an array $array:array("i", "love", "iwind"). Similar functions to the explode function include: preg_split(), spliti(), split() and other functions.

In contrast, implode and join can combine an array into a string. They are functions with exactly the same functionality.


$array = array("i", "love", "iwind");
$str = implode(" ", $array);

Example The implode function concatenates each element of the array $array with a space character and returns a string $str: "i love iwind".

Crop

A string head and tail, It may not be the part you want, so you can use trim, rtrim, ltrim and other functions to remove spaces at both ends of a string, spaces at the end of a string, and spaces at the beginning of a string.


echo trim(" i love iwind "); // will get "i love iwind"
echo rtrim(" i love iwind "); // will get " i love iwind"
echo ltrim(" i love iwind "); // You will get "i love iwind "

In fact, these three parameters can not only remove the spaces at the beginning and end of the string, but also remove their second The characters specified by the parameters, such as:


echo trim(",1,2,3,4,", ","); // will get the " at both ends of 1,2,3,4 ," was cut.

Sometimes you will see people using the chop function. In fact, it is a synonymous function for rtrim.
Case

For English letters, you can use strtoupper and strtolower to convert them into uppercase or lowercase.


echo strtoupper("i love iwind"); // will get I LOVE IWIND
echo strtolower("I LOVE IWIND"); // will get i love iwind

Comparison

Generally, you can use !=, == to compare whether two objects are equal. The reason why they are two objects is because they are not necessarily all strings, they can also be integers, etc. For example


$a = "joe";
$b = "jerry";
if ($a != $b)
{
echo "not equal ";
}
else
{
echo "Equal";
}

If you use !==,===(you can see an extra equal sign ) for comparison, the types of the two objects must be strictly equal to return true; otherwise, using ==,!= will automatically convert the string into the corresponding type for comparison.


22 = = "22"; // Return true
22 === "22"; // Return false
Because of this, some unexpected "accidents" often occur in our program:
0 = = "I love you"; // Return true
1 == "1 I love you"; // Return true

There is also a set of functions for string comparison in PHP: strcmp , strcasecmp, strncasecmp(), strncmp(), they all return an integer greater than 0 if the former is greater than the latter; if the former is less than the latter, return an integer less than 0; if they are equal, return 0 .The principles of their comparison are the same as the rules of other languages.
strcmp is used for case-sensitive (i.e. case-sensitive) string comparison:


echo strcmp("abcdd", "aBcde"); // Returns 1 (>0 ), comparing "b" and "B"

strcasecmp is used for case-insensitive string comparison:


echo strcasecmp("abcdd", "aBcde") ; // Return -1 (
strncmp is used to compare part of the string, starting from the beginning of the string, the third parameter, For the length to be compared:


echo strncmp("abcdd", "aBcde", 3); // Returns 1 (>0), compared abc and aBc

strncasecmp is used to compare part of a string without case sensitivity, starting from the beginning of the string. The third parameter is the length to be compared:


echo strncasecmp("abcdd", " aBcde", 3); // Returns 0, compared abc and aBc, since they are not case-sensitive, they are the same.

There is another situation where simply comparing the string sizes cannot meet our predetermined requirements. For example, normally 10.gif will be larger than 5.gif, but if you apply the above functions, it will return - 1, which means 10.gif is better than 5.gif. For this situation, PHP provides two natural contrast functions strnatcmp and strnatcasecmp:


echo strnatcmp("10.gif", "5 .gif"); // Return 1 (>0)
echo strnatcasecmp("10.GIF", "5.gif"); // Return 1 (>0)

Replace

The meaning of substitution is to change part of a string to make it a new string to meet new requirements. In PHP, str_replace("content to be replaced", "string to replace the original content", "original string") is usually used for replacement.


echo str_replace("iwind", "kiki", "i love iwind, iwind said"); // Will output "i love kiki, kiki said"
will be in the original string All "iwind" are replaced with "kiki".

str_replace is case-sensitive, so you cannot imagine using str_replace("IWIND", "kiki",...) to replace the original string "iwind" in.

str_replace can also achieve many-to-one and many-to-many replacement, but it cannot achieve one-to-many replacement:


echo str_replace(array(" iwind", "kiki"), "people", "i love kiki, iwind said");
will output
i love people, people said
array("iwind" in the first parameter ", "kiki") were replaced with "people"

echo str_replace(array("iwind", "kiki"), array("gentle man", "ladies"), "i love kiki , iwind said");
Output i love ladies, gentle man said. That is to say, the elements in the first array are replaced by the corresponding elements in the second array. If one array has fewer elements than the other, the remaining elements will be treated as empty.

Somewhat similar to this is strtr, please refer to the manual for usage.

In addition, PHP also provides substr_replace to replace part of the string. The syntax is as follows:
substr_replace (original string, string to be replaced, starting replacement position [, replacement length])
Among them, the starting replacement position is calculated from 0 and should be less than the length of the original string . The length to replace is optional.
echo substr_replace("abcdefgh", "DEF", 3); // Will output "abcDEF"
echo substr_replace("abcdefgh", "DEF", 3, 2); // Will output "abcDEFfgh"
In the first example, the replacement starts from the third position (i.e. "d"), thereby replacing "defgh" with "DEF"
In the second example, it also starts from the third position (i.e. "d") starts to replace, but it can only replace 2 lengths, that is, to e, so "de" is replaced with "DEF".

PHP also provides preg_replace, preg_replace_callback, ereg_replace, Functions such as eregi_replace apply regular expressions to complete string replacement. Please refer to the manual for usage.
Search and match

There are many functions in PHP for searching, matching or positioning, and they all have different meanings. Here we only talk about the more commonly used strstr and stristr. The functions and return values ​​of the latter and the former are the same, but they are not case-sensitive.
strstr("parent string", "substring") is used to find the first occurrence of the substring in the parent string, and returns the position from the beginning of the substring to the parent string in the parent string Ending part. For example


echo strstr("abcdefg", "e"); //will output "efg"
If the substring is not found, it will return empty.Because it can be used to determine whether a string contains another string:
$needle = "iwind";
$str = "i love iwind";
if (strstr($str, $needle ))
{
echo "There is iwind inside";
}
else
{
echo "There is no iwind inside";
}
will output "Inside There is iwind"

HTML related

1,htmlspecialchars($string)

This is its simplest usage, convert some special characters in the string (as the name suggests)& ,',"Convert into their corresponding HTML entity forms:


$str = "i love kiki, iwind said.";
echo htmlspecialchars($str);

will output
i love kiki, iwind said.

2,htmlentities($string)

Convert all characters that can be converted into entity form into entity form

3,html_entity_decode($string);

Added after PHP4.3.0 and htmlentities($string). The opposite function.

4,nl2br($string)

Converts all newline characters in the string to + newline characters. For example:


$str = "i love kiki,n iwind said.";
echo nl2br($str);

will output
i love kiki,

iwind said.

Encryption

The most commonly used method of encrypting strings is md5, which converts a string into a 32-bit unique string

<.>echo md5("i love iwind"); // Will output "2df89f86e194e66dc54b30c7c464c21c"

PHP5 adds a second parameter to md5, so that it can output a 16-bit encrypted string.

At this point, this introductory tutorial on string operations is over, but the above is just the tip of the iceberg. Especially since PHP5 has added a lot of new features, we need to continue to learn. Only then can it be applied well.

http://www.bkjia.com/PHPjc/317290.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317290.htmlTechArticleNo matter which language, string operation is an important foundation, often simple and important. Just like human speech, it generally has a body (graphical interface) and language (print string?)...
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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.