Строки РНР это последовательность символов, используется для хранения и манипуляций с текстом. Есть как минимум два способа указать строку, это одинарные кавычки и двойные кавычки.
Вы можете создать строку заключив текст в одинарные кавычки. Это простой способ указания строк в РНР
<?php $str='Hello text within single quote'; echo $str; ?>
Output Hello text within single quote
В одинарные кавычки вы можете заключить многострочный текст, специальные символы и эскейп-последовательность:
<?php $str1='Hello text multiple line text within single quoted string'; $str2='Using double "quote" directly inside single quoted string'; $str3='Using escape sequences \n in single quoted string'; echo "$str1
$str2
$str3"; ?>
Output: Hello text multiple line text within single quoted string Using double "quote" directly inside single quoted string Using escape sequences \n in single quoted string
Примечание. В строках PHP с одинарными кавычками большинство escape-последовательностей
и переменных не будут интерпретироваться. Но мы можем использовать
обратный след для экранирования кавычки \'
и для экранирования самого обратного слеша \\.
<?php $num1=10; $str1='trying variable $num1'; $str2='trying backslash n and backslash t inside single quoted string \n \t'; $str3='Using single quote \'my quote\' and \\backslash'; echo "$str1
$str2
$str3"; ?>
Output: trying variable $num1 trying backslash n and backslash t inside single quoted string \n \t Using single quote 'my quote' and \backslash
В РНР мы так же можем заключать текст в двойные кавычки. Но escape-последовательности и переменные будут интерпретироваться с использованием строк PHP с двойными кавычками.
<?php $str="Hello text within double quote"; echo $str; ?>
Output: Hello text within double quote
Сейчас вы не можете использовать двойные кавычки непосредственно в строке заключённой в двойные кавычки
<?php $str1="Using double "quote" directly inside double quoted string"; echo $str1; ?>
Output: Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on line 2
Мы можем хранить многострочный текст, специальные символы и эскейп-последовательности в строках заключённых двойными кавычками.
<?php $str1="Hello text multiple line text within double quoted string"; $str2="Using double \"quote\" with backslash inside double quoted string"; $str3="Using escape sequences \n in double quoted string"; echo "$str1
$str2
$str3"; ?>
Output: Hello text multiple line text within double quoted string Using double "quote" with backslash inside double quoted string Using escape sequences in double quoted string
В двойных кавычках переменная будет интерпретироваться.
<?php $num1=10; echo "Number is: $num1"; ?>
Output: Number is: 10
PHP предоставляет функции для доступа и управления строками. Ниже дан список некоторых важных строковых функций:
Строковые функции РНР. | |
|---|---|
| Функция | Описание |
| addcslashes() | Используется для возврата строки с обратными слешами. |
| addslashes() | Используется для возврата строки с обратными слешами. |
| bin2hex() | Он используется для преобразования строки символов ASCII в шестнадцатеричные значения. |
| chop() | Удаляет пробелы или другие символы с правого конца строки |
| chr() | Используется для возврата символов со специальными ASCII значениями. |
| chunk_split() | It is used to split a string into a series of smaller parts. |
| convert_uuencode() | It is used to encode a string using the uuencode algorithm. |
| count_chars() | It is used to return information about characters used in a string. |
| crc32() | It is used to calculate a 32-bit CRC for a string. |
| crypt() | It is used to create hashing string One-way. |
| echo() | It is used for output one or more strings. |
| explode() | It is used to break a string into an array. |
| hebrev() | It is used to convert Hebrew text to visual text. |
| hebrevc() | It is used to convert Hebrew text to visual text and new lines (\n) into <br>. |
| hex2bin() | It is used to convert string of hexadecimal values to ASCII characters. |
| print() | It is used for output one or more strings. |
| fprint() | It is used to write a formatted string to a stream. |
| nl2br() | It is used to insert HTML line breaks in front of each newline in a string. |
| number_format() | It is used to format a number with grouped thousands. |
| htmlentities() | It is used to convert character to HTML entities. |
| html_entity_decode() | It is used to convert HTML entities to characters. |
Функция strtolower() возвращает строку буквами в нижнем регистре.
Синтаксис:
string strtolower ( string $string )
Пример:
<?php $str="My name is KARAN"; $str=strtolower($str); echo $str; ?>
Output: my name is karan2) PHP strtoupper() function The strtoupper() function returns string in uppercase letter. Syntax string strtoupper ( string $string ) Example
<?php $str="My name is KARAN"; $str=strtoupper($str); echo $str; ?>
Output: MY NAME IS KARAN3) PHP ucfirst() function The ucfirst() function returns string converting first character into uppercase. It doesn't change the case of other characters. Syntax string ucfirst ( string $str ) Example
<?php $str="my name is KARAN"; $str=ucfirst($str); echo $str; ?>
Output: My name is KARAN4) PHP lcfirst() function The lcfirst() function returns string converting first character into lowercase. It doesn't change the case of other characters. Syntax string lcfirst ( string $str ) Example
<?php $str="MY name IS KHAN"; $str=lcfirst($str); echo $str; ?>
Output: mY name IS KHAN5) PHP ucwords() function The ucwords() function returns string converting first character of each word into uppercase. Syntax string ucwords ( string $str ) Example
<?php $str="my name is Khan karan"; $str=ucwords($str); echo $str; ?>
Output: My Name Is Khan Karan6) PHP strrev() function The strrev() function returns reversed string. Syntax string strrev ( string $string ) Example
<?php $str="my name is karan"; $str=strrev($str); echo $str; ?>
Output: narak si eman ym7) PHP strlen() function The strlen() function returns length of the string. Syntax int strlen ( string $string ) Example
<?php $str="my name is karan"; $str=strlen($str); echo $str; ?>
Output: 16