/ / PHP: working with strings. PHP string functions

PHP: working with strings. PHP String Functions

Сайты можно разделить на статические и dynamic. After mastering HTML and CSS, which allow you to make a beautiful business card on the Internet, many people think how to create a dynamic website in PHP. At the same time, the coder must take into account that now he is starting to learn web programming: the principles of working with the site will be different. One of the first problems that a beginner faces in PHP is working with strings, reading and processing them.

PHP work with strings
It is worth noting that in PHP functions of working withstrings imply a large number of methods, so you should start learning them with the simplest manipulations, such as printing a string, searching for, getting or replacing a substring, changing the case and returning the length of the string. Many functions do not work well 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, simply by removing the semicolon.

Create and output a string

We will analyze the line output on the screen using the well-known language construct echo. The programmer can print the 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 print several lines in one, then they resort to concatenation:

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

or

$ str1 = "This is";

$ str2 = "New";

$ str3 = "String";

echo $ str1. $ str2. $ str3;

In the latter case, the screen will be displayed. This is a NewString. You can add a space immediately when you call echo:

echo $ str1. "". $ str2. "". $ str3;

In this case, the screen will display: "This is a New Line". Concatenation is possible not only when outputting, but also when creating a string:

$ str1 = "This is";

$ str2 = "New";

$ str3 = "String";

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

echo $ string;

Echo displays both Latin and Cyrillic letters. If one of the variables contained a number, then during concatenation this number will be converted to the corresponding string:

$ and = 2;

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

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

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

php site

Service symbols

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

  • n makes a line break;
  • r returns the carriage;
  • "escapes double quotes:
    • echo "String with" double quotes "; // String with double quotes
  • $ shields a dollar;
  • \ escapes the backslash.

There are much 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

Suppose we have a simple line:

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

We also have two lines with names:

$ name = "Emelyan";

$ another Name = "Katherine";

We need to know if the first line containsthese two names. The function strpos ($ str, $ search) is used for this. It returns the position of the required $ search substring if this string is contained in the source, $ str. Otherwise, the function returns a boolean false. For example, strpos ($ string, $ anotherName) returns false, and strpos ($ string, $ name) returns an integer. The code will be like this (let's write an option when the position is displayed on the screen):

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

$ name = "Emelyan";

$ another Name = "Katherine";

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

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

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

Search for the position of the last occurrence of substrings and pitfalls

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

There are some pitfalls associated withthe beginning of the 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 comparison operation with negation: strpos ($ str, $ search)! = False. In any version of PHP, examples with a similar equivalent may not work correctly, because the numbering of lines starts from zero, and in logical interpretation 0 is false. This also applies to the strrpos () function.

How to find the number of occurrences of a substring

Often you need to find not the position of the first orthe last occurrence of a substring in a string, and 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 area by string, then two more variables are passed to the function: the beginning and end of the string, respectively. That is, the function in this case is called like this: substr_count ($ str, $ search, $ start, $ end). The function will search for the $ search substring from $ start to $ end of the original $ str string. If the string is not found, the function will return zero.

Web programming

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

Case change is often used tostring comparisons and conditional statements. Suppose a user must enter the name of the supreme god in Norse 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 text (for example, the user writes "one" or "ONE"), the program will return false instead of true. To avoid this, use the case change function. This is often used if the PHP site 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 returns 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 needed in creating a loop. To search for a string, use the strlen () function, 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 substrings in PHP: working with strings

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

To replace a substring, use the functionstr_replace (), which accepts three variables: str_replace ($ subStr, $ newSub, $ str). Unlike many functions, str_replace () works correctly with Cyrillic characters and has no counterpart with a prefix. Example:

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

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

Line feed to number

php examples
Каждому, кто изучает веб-программирование, рано or later you have to translate the string into a number. Two similar functions are used for this: intval () and floatval (), each of which accepts one $ string variable. 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, and they will be converted to a number. If after the numbers will be any set of letters, they are simply ignored. In the event that a string starts with letters, the use of the function will return zero. Ideally, the line should contain only numbers.

Converting a number to a string

Often it is required to translate numbers into a string.Let's say if you need to take a half of a number and square it (for example, check whether 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 the new line, you can perform all other actions: change, search for the occurrence of a substring and other functions. If necessary, the string can be re-translated into a number already described above.

php string functions
В статье была рассмотрена лишь малая часть всех functions associated with strings. Some of the undescribed functions work with symbols, but a large one was not included in the material due to its specificity. To familiarize yourself with these features, you must go to the reading of the official PHP documentation, which displays relevant information.