PHP: working with strings. PHP String Functions

Sites can be divided into static and dynamic. After mastering HTML and CSS, which allow you to make a beautiful business card on the Internet, many think about how to create a dynamic site in PHP. At the same time, the layout designer should take into account that he is now starting to learn web programming: the principles of working with the site will differ. One of the first problems a beginner faces in PHP is working with strings, reading and processing them.

PHP string handling
It is worth noting that in PHP string functions mean a large number of methods, so you should start learning them with the most simple manipulations, such as outputting a string, finding, getting or replacing a substring, changing case and returning the length of the string. Many functions work poorly with Cyrillic characters. Therefore, all examples are written in English for clarity. For Cyrillic strings, the same functions are used, but with the prefix mb_ (for example, mb_strpos ()). Before using analogs, in php.ini you need to uncomment the line; extension = php_mbstring.dll, just removing the semicolon.

Create and output a string

We will analyze the output of a string to the screen using the well-known echo language construct. The programmer can print a line immediately:

echo "This is a New Line"

or create a variable first and then display it:

$ str = "This is a New Line";

echo $ str;

If you need to output several lines in one, then resort to their concatenation:

echo "This." "New". " Line";

or

$ str1 = "This";

$ str2 = "New";

$ str3 = "String";

echo $ str1. $ str2. $ str3;

In the latter case, This is a New String . A space can be added immediately when calling echo:

echo $ str1. ''. $ str2. ''. $ str3;

In this case, the screen displays: "This is a New Line." Concatenation is possible not only during output, but also when creating a string:

$ str1 = "This";

$ str2 = "New";

$ str3 = "String";

$ string = $ str1. ''. $ str2. ''. $ str3;

echo $ string;

Echo prints both latin and cyrillic letters . If one of the variables contained a number, then upon concatenation this number will be converted to the corresponding line:

$ i = 2;

$ sum = $ i + $ i; // now $ sum contains the number 4

echo $ i. "+". $ i. "=". $ sum;

The screen will display: "2 + 2 = 4".

php website

Service symbols

Suppose a string is defined using double quotes ($ string = "Like this"). Then you can quite safely use escape sequences:

  • \ n does a line feed;
  • \ r returns a carriage;
  • \ "escapes double quotes:
    • echo "String with \" double \ "quotation marks"; // String with double quotes
  • \ $ screens dollar;
  • \\ escapes backslashes.

There are many more sequences, all of them can be found in the official PHP documentation.

How to find the position of the first occurrence of a substring

Let's say we have a simple line:

$ string = "My name is Yemelyan and I am 27 year old";

We also have two lines with names:

$ name = "Yemelyan";

$ anotherName = "Katherin";

We need to find out if the first line contains these two names. To do this, use the strpos ($ str, $ search) function. It returns the position of the desired substring $ search, if this string is contained in the original, $ str. Otherwise, the function returns a Boolean value of false. For example, strpos ($ string, $ anotherName) will return false, and strpos ($ string, $ name) will return an integer. The code will be like this (we’ll write an option when the position is displayed on the screen):

$ string = "My name is Yemelyan and I am 27 year old";

$ name = "Yemelyan";

$ anotherName = "Katherin";

echo strpos ($ string, $ anotherName); // print false

echo strpos ($ string, $ name); // print the position of the first occurrence of the substring

Note that line numbering starts from zero, that is, in our case, the last line will print the number 11 (spaces are also considered).

Finding the position of the last occurrence of a substring and pitfalls

If the strpos () function returns the position of the first occurrence, then the inverse strrpos () function searches for the last occurrence of the substring.

There are some pitfalls associated with the start of numbering. This is worth considering: in PHP, working with strings can be complicated by limitations in comparisons. So, it is better not to use the negation comparison operation: strpos ($ str, $ search)! = False. In any version of PHP, examples with such equivalents may not work correctly, because line numbering starts from zero, and in the logical interpretation, 0 is false. This extends to the strrpos () function.

How to find the number of substring occurrences

Often you need to find not the position of the first or last occurrence of a substring in a string, but their total number. To do this, use the substr_count () function, which processes at least two variables: substr_count ($ str, $ search). Returns an integer. If it is necessary to reduce the search by line, then two more variables are passed to the function: the beginning and end of the line, respectively. That is, the function in this case is called like this: substr_count ($ str, $ search, $ start, $ end). The function will search for the substring $ search between $ start and $ end of the original string $ str. If the string is not found, then the function will return zero.

Web programming

How to change the case of a string in PHP: examples

Case change is often used to compare strings and conditional statements. Suppose a user has to enter the name of the supreme god in Scandinavian mythology. The program has the option "One", with which the user's response will be compared. If the entered text does not match the existing one (for example, the user writes β€œone” or β€œONE”), the program will return false instead of true. To avoid this, the case change function is used. This is often used if the site in PHP has tags: instead of hundreds of variants of the word "personal" ("Personal", "personal", "PERSONAL", etc.) there is only one tag in lower case.

The strtolower () function changes case to lower case. Suppose there is a line $ catName = "Fluffy". The strtolower ($ catName) function will return the string "fluffy". You can change the case to upper case using the strtoupper () function.

How to find the length of a string in PHP: working with functions

Often you need to find the length of the string. For example, in PHP, working with strings of this kind may be necessary in creating a loop. To search for a string, the strlen () function is used, which returns a number - the number of characters. We must not forget that the last character will have the number strlen ($ str) -1, since the numbering starts from zero.

php work

Getting and replacing a substring in PHP: working with strings

The substring is obtained by the substr () function, which can take two or three arguments: substr ($ str, $ start, $ end). Suppose we have a string $ string = "Fluffy cat", and we want to get a substring from the second to fourth character. Since the numbering starts from zero, the variable with this substring will look like this: $ newString = substr ($ string, 1, 4). If we introduce $ newString = substr ($ string, 1), we get a substring from the second character to the last (that is, "luffy"). This code is identical to the full string code using strlen (): substr ($ string, 1, strlen ($ string)).

To replace the substring, the str_replace () function is used, which takes three variables: str_replace ($ subStr, $ newSub, $ str). Unlike many functions, str_replace () works correctly with Cyrillic characters and has no analogue with a prefix. Example:

$ str = "The weather is terrible today!";

$ newStr = str_replace ("terrible", "wonderful", $ str); // Today the weather is wonderful!

Convert string to number

php examples
Everyone who studies web programming will sooner or later have to translate a string into a number. Two similar functions are used for this: intval () and floatval (), each of which takes one variable $ string. They differ from each other only in the type of data returned: intval () returns an integer, and floatval () - a floating-point number.

To use both intval () and floatval (), it is necessary that the string starts with numbers, they will be converted to a number. If any set of letters comes after the numbers, they will simply be ignored. If the line starts with letters, using the function will return zero. Ideally, the string should contain only numbers.

Convert a number to a string

Often you need to translate numbers into a string. Say, if you need to take half of the number and square it (for example, check if the equality holds: 88 x 88 + 33 x 33 = 8833). In this case, the strval () function is used, which returns a string with a number. After that, with a new line, you can perform all other actions: change, search for the substring and other functions. If necessary, the string can again be converted to a number as described above.

php string functions
Only a small fraction of all string related functions was considered in the article. Some of the undescribed functions work with symbols, but a large part was not included in the material due to specificity. To familiarize yourself with these features, you need to go on to read the official PHP documentation, which displays up-to-date information.

Source: https://habr.com/ru/post/K4608/


All Articles