A string is a collection of characters. String is one of the data types supported by PHP. The string variables can contain alphanumeric characters. Strings are created when;
- You declare variable and assign string characters to it
- You can directly use them with echo statement.
- String are language construct, it helps capture words.
Single-Quoted Strings
Single-quoted strings do not interpolate variables. Thus, the variable name in the following string is not expanded because the string literal in which it occurs is singlequoted:$name = 'Fred';
$str = 'Hello, $name'; // single-quoted
echo $str;
Hello, $name
The only escape sequences that work in single-quoted strings are \', which puts a single quote in a single-quoted string, and \\, which puts a backslash in a single-quoted string. Any other occurrence of a backslash is interpreted simply as a backslash:
$name = 'Tim O\'Reilly';// escaped single quote
echo $name;
$path = 'C:\\WINDOWS'; // escaped backslash
echo $path;
$nope = '\n'; // not an escape
echo $nope;
Tim O'Reilly
C:\WINDOWS
\n
Double-Quoted Strings
Double-quoted strings interpolate variables and expand the many PHP escape sequences. Table lists the escape sequences recognized by PHP in double-quoted strings.If an unknown escape sequence (i.e., a backslash followed by a character that is not one of those in Table ) is found in a double-quoted string literal, it is ignored (if you have the warning level E_NOTICE set, a warning is generated for such unknown escape sequences):
$str = "What is \c this?";// unknown escape sequence
echo $str;
What is \c this?
Creating And Accessing Strings
As you learned in previous section, creating a string variable is as simple as assigning a literal string value to a new variable name.Both single and double quote are used to create string.
Syntax:
$var=”shubhneet”;
$my_variable = ” hello ” ;
Using Your Own Delimiters
Although quotation marks make good delimiters for string literals in most situations, sometimes it helps to be able to use your own delimiter. For example, if you need to specify a long string containing lots of single and double quotation marks, it ‟ s tedious to have to escape many quotation marks within the string.You can use your own delimiters in two ways: heredoc syntax and nowdoc syntax. Heredoc is the equivalent of using double quotes: variable names are replaced with variable values, and you can use escape sequences to represent special characters. Nowdoc works in the same way as single quotes: no variable substitution or escaping takes place; the string is used entirely as - is.
Heredoc syntax works like this:
$myString = < < < DELIMITER
(insert string here)
DELIMITER;
Nowdoc syntax is similar; the only difference is that the delimiter is enclosed within single quotes:
$myString = < < < ‟DELIMITER‟
(insert string here)
DELIMITER;
Printing Strings
There are four ways to send output to the browser. The echo construct lets you print many values at once, while print() prints only one value. The printf() function builds a formatted string by inserting values into a template. The print_r() function is useful for debugging—it prints the contents of arrays, objects, and other things, in a moreor- less human-readable form.echo
echo "Printy";echo("Printy"); // also valid
print()
The print() construct sends one value (its argument) to the browser:if (print("test")) {
print("It worked!");
}
It worked!
printf()
The printf() function outputs a string built by substituting values into a template (the format string). It is derived from the function of the same name in the standard C library. The first argument to printf() is the format string. The remaining arguments are the values to be substituted. A % character in the format string indicates a substitutionFormat modifiers
Each substitution marker in the template consists of a percent sign (%), possibly followed by modifiers from the following list, and ends with a type specifier. (Use %% to get a single percent character in the output.) The modifiers must appear in the order in which they are listed here:
- A padding specifier denoting the character to use to pad the results to the appropriate string size. Specify 0, a space, or any character prefixed with a single quote. Padding with spaces is the default.
- A sign. This has a different effect on strings than on numbers. For strings, a minus (-) here forces the string to be left-justified (the default is to right-justify). For numbers, a plus (+) here forces positive numbers to be printed with a leading plus sign (e.g., 35 will be printed as +35).
- The minimum number of characters that this element should contain. If the result would be less than this number of characters, the sign and padding specifier govern how to pad to this length.
- For floating-point numbers, a precision specifier consisting of a period and a number; this dictates how many decimal digits will be displayed. For types other than double, this specifier is ignored.
print_r() and var_dump()
The print_r() construct intelligently displays what is passed to it, rather than casting everything to a string, as echo and print() do. Strings and numbers are simply printed.
Arrays appear as parenthesized lists of keys and values, prefaced by Array:
$a = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
print_r($a);
Array
(
[name] => Fred
[age] => 35
[wife] => Wilma
)
Using print_r() on an array moves the internal iterator to the position of the last element in the array.
String Operations:
1. Finding the Length of a String
Once you have a string variable, you can find out its length with the strlen() function. This function takes a string value as an argument, and returns the number of characters in the string. For example:
$myString = “hello”;
echo strlen( $myString ) . “ < br / > ”; // Displays 5
echo strlen( “goodbye” ) . “ < br / > ”; // Displays 7
2. Accessing Characters within a String
You might be wondering how you can access the individual characters of a string. PHP makes this easy for you. To access a character at a particular position, or index , within a string, use:
$character = $string[index];
$myString = “Hello, world!”;
echo $myString[0] . “ < br / > ”; // Displays „H‟
echo $myString[7] . “ < br / > ”; // Displays „w‟
$myString[12] = „?‟;
echo $myString . “ < br / > ”; // Displays „Hello, world?‟
If you need to extract a sequence of characters from a string, you can use PHP ‟ s substr() function. This function takes the following parameters: The string to extract the characters from The position to start extracting the characters. If you use a negative number, substr() counts backward from the end of the string The number of characters to extract. If you use a negative number, substr() misses that many characters from the end of the string instead. This parameter is optional; if left out, substr() extracts from the start position to the end of the string Here are a few examples that show how to use substr() :
$myString = “Hello, world!”;
echo substr( $myString, 0, 5 ) . “ < br/ > ”; // Displays „Hello‟
echo substr( $myString, 7 ) . “ < br/ > ”; // Displays „world!‟
echo substr( $myString, -1 ) . “ < br/ > ”; // Displays „!‟
echo substr( $myString, -5, -1 ) . “ < br/ > ”; // Displays „orld‟
Searching Strings
- strstr() tells you whether the search text is within the string
- strpos() and strrpos() return the index position of the first and last occurrence of the search text, respectively
- substr_count() tells you how many times the search text occurs within the string
- strpbrk() searches a string for any of a list of characters
strstr()
strstr() takes two parameters: the string to search through, and the search text. If the text is found, strstr() returns the portion of the string from the start of the found text to the end of the string. If the text isn ‟ t found, it returns false . For example:
$myString = “Hello, world!”;echo strstr( $myString, “wor” ) . “ < br / > ”; // Displays „world!‟
echo ( strstr( $myString, “xyz” ) ? “Yes” : “No” ) . “ < br / > ”; // Displays „No‟
strpos() and strrpos()
strpos() function takes the same two parameters as strstr() : the string to search, and the search text to look for. If the text is found, strpos() returns the index of the first character of the text within the string. If it ‟ s not found, strpos() returns false :
$myString = “Hello, world!”;
echo strpos( $myString, “wor” ); // Displays „7‟
echo strpos( $myString, “xyz” ); // Displays „‟ (false)
strpos() has a sister function, strrpos() , that does basically the same thing; the only difference is that strrpos() finds the last match in the string, rather than the first:
$myString = “Hello, world!”;
echo strpos( $myString, “o” ) . “ < br / > ”; // Displays „4‟
echo strrpos( $myString, “o” ) . “ < br / > ”; // Displays „8‟
substr_count()
the number of occurrences easily enough using strpos() and a loop, but PHP, as in most other things, gives you a function to do the job for you: substr_count() . To use it, simply pass the string to search and the text to search for, and the function returns the number of times the text was found in the string. For example:
$myString = “I say, nay, nay, and thrice nay!”;
echo substr_count( $myString, “nay” ); // Displays „3‟
strpbrk()
strpbrk() lets you easily carry out such a search. It takes two arguments: the string to search, and a string containing the list of characters to search for. The function returns the portion of the string from the first matched character to the end of the string. If none of the characters in the set are found in the string, strpbrk() returns false . Here are some examples:
$myString = “Hello, world!”;
echo strpbrk( $myString, “abcdef” ); // Displays „ello, world!‟
echo strpbrk( $myString, “xyz” ); // Displays „‟ (false)
$username = “matt@example.com”;
if ( strpbrk( $username, “@!” ) ) echo “@ and ! are not allowed in usernames”;
Replacing Text within Strings
As well as being able to search for text within a larger string, you can also replace portions of a string with different text. This section discusses three useful PHP functions for replacing text:
- str_replace() replaces all occurrences of the search text within the target string
- substr_replace() replaces a specified portion of the target string with another string
- strtr() replaces certain characters in the target string with other characters
str_replace()
str_replace() lets you replace all occurrences of a specified string with a new string. The function takes three arguments: the search string, the replacement string, and the string to search through. It returns a copy of the original string with all instances of the search string swapped with the replacement string. Here ‟ s an example:
$myString = “It was the best of times, it was the worst of times,”;
// Displays “It was the best of bananas, it was the worst of bananas,”
echo str_replace( “times”, “bananas”, $myString );
substr_replace()
Whereas str_replace() searches for a particular string of text to replace, substr_replace() replaces a specific portion of the target string. To use it, pass three arguments: the string to work on, the replacement text, and the index within the string at which to start the replacement. substr_replace() replaces all the characters from the start point to the end of the string with the replacement text, returning the modified string as a copy (the original string remains untouched).
This example shows how substr_replace() works:
$myString = “It was the best of times, it was the worst of times,”;
// Displays “It was the bananas”
echo substr_replace( $myString, “bananas”, 11 ) . “ < br/ > ”;
strtr()
strtr() function takes three arguments: the string to work on, a string containing a list of characters to translate, and a string containing the characters to use instead. The function then returns a translated copy of the string. So you could write a simple script to make a “ URL friendly ” string as follows:
$myString = “Here‟s a little string”;
// Displays “Here-s+a+little+string”
echo strtr( $myString, “ „”, “+-” ) . “ < br/ > ”;
strtr() is especially useful if you need to translate a string from one character set to another, because you can easily map hundreds of characters to their equivalents in the new character set just by passing a couple of strings.
DOWNLOAD OUR OFFICIAL APP FOR FREE
File name: ProgrammingWorld.apk
Size : 19mb
Features : E-learning notes, video lactures,group chat,
support 24 x 7



No comments:
Post a Comment