phpmysql1.2

 

Strings

A string is simply a sequence of characters.

Example:  “hello” , “how are you?” , “123”, and “!@#$%” are all valid string values.

 

Creating and Accessing Strings

Creating a string variable is as simple as assigning a literal string value to a new variable name:

$myString = ‘hello‘;

 

In this example, the string literal ( hello ) is enclosed in single quotation marks ( ‘ ). You can also use double quotation marks ( “ ), as follows:

$myString = “hello”;

 

If you enclose a string in single quotation marks, PHP uses the string exactly as typed. However, double quotation marks give you a couple of extra features:

·         Any variable names within the string are parsed and replaced with the variable ’ s value

·         You can include special characters in the string by escaping them

Examples:

$myString = ‘world’;

echo “Hello, $myString! <br/> ”;                             // Displays “Hello, world!”

echo ‘Hello, $myString! <br/ > ’;                              // Displays “Hello, $myString!”

echo “ <pre> Hi\tthere! </pre> ”;                           // Displays “Hi there!”

echo ‘ <pre> Hi\tthere! </pre> ’;                             // Displays “Hi\tthere!”

With the “Hi there!” example, an escaped tab character ( \t ) is included within the string literal. When double quotes are used, the \t is replaced with an actual tab character; hence the big gap between Hi and there! in the output.

 


 

Including More Complex Expressions within Strings

You can use the curly brackets to distinguish the variable name from the rest of the string.

$favoriteAnimal = “cat”;

echo “My favorite animals are {$favoriteAnimal}s”;

or

echo “My favorite animals are ${favoriteAnimal}s”;

 

This produces the expected result:

My favorite animals are cats

 

You can use this curly bracket syntax to insert more complex variable values, such as array element values and object properties.

Example:

$myArray[“age”] = 34;

echo “My age is {$myArray[“age”]}”;                                  // Displays “My age is 34”

 

Using Your Own Delimiters

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.

Heredoc syntax :

 

$myString = <<<DELIMITER (insert string here) DELIMITER;

 

DELIMITER is the string of text you want to use as a delimiter. It must contain just letters, numbers, and

underscores, and must start with a letter or underscore. Traditionally, heredoc delimiters are written in

uppercase, like constants.

 

Here ’ s an example of heredoc syntax in action:

 

$name = ‘Mahadev’;

$myString = <<< END_TEXT

“’I am  $name,’ he said ‘In the Drama!’”

END_TEXT;

echo “ <pre> $myString </pre> ”;

 

This example displays the following output:

 “’I am  Mahadev,’ he said ‘In the Drama!’”

 

Nowdoc works in the same way as single quotes: no variable substitution or escaping takes place; the string is used entirely as - is.

 

Nowdoc syntax is similar; the only difference is that the delimiter is enclosed within single quotes:

 

$myString = <<< ’ DELIMITER ’ (insert string here) DELIMITER;

 

Here ’ s the same example using nowdoc syntax instead:

$name = ‘Mahadev’;

$myString = <<< ’END_TEXT ’

“’I am  $name,’ he said ‘In the Drama!’”

END_TEXT;

echo “ <pre> $myString </pre> ”;

 

Output: (notice that  $name variable is not substituted this time):

“’I am  $name,’ he said ‘In the Drama!’”

 

Other Ways to Create Strings

You don ’ t have to assign a literal string value to create a string variable; you can assign the result of

any expression:

 

$myString = $yourString;

$myString = “how “ . “are “ . “you?”;

$myString = ( $x > 100 ) ? “Big number” : “Small number”;

 

Finding the Length of a String

The PHP strlen() function returns the length of a string.

For example:

$myString = “hello”;

echo strlen( $myString ) . “ <br/> ”;    // Displays 5

echo strlen( “goodbye” ) . “ <br/> ”;    // Displays 7

 

str_word_count():

The PHP str_word_count() function counts the number of words in a string.

echo str_word_count( “Hello, world!” );          // Displays 2

 

Accessing Characters within a String

To access a character at a particular position, or index , within a string, use:

$character = $string[index];

Example:

$myString = “Hello, world!”;

echo $myString[0] . “ <br/> ”;                     // Displays ‘H’

$myString[12] = ‘?’;

echo $myString . “ <br/> ”;              // Displays ‘Hello, world?’

substr()

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:

 

substr(string,start,length)

 

·         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() :

<?php

$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’  Here -1 value ! will be ignored

?>                                                                    //Remaining characters will be printed

 

Searching Strings

PHP gives you several string functions that let you search for one string inside another

 Searching Strings with strstr()

 If you just want to find out whether some text occurs within a string, use strstr() . This 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 .

strstr(string,search,before_search)

 For example:

$myString = “Hello, world!”;

echo strstr( $myString, “wor” ) . “ <br/> ”;                                    // Displays ‘world!’

 If you pass in a value of true , strstr() instead returns the portion from the start of the string to the character before the found text:

$myString = “Hello, world!”;

echo strstr( $myString, “wor”, true );                                              // Displays ‘Hello, ‘

 

Locating Text with strpos() and strrpos()

To find out exactly where a string of text occurs within another string, use strpos() . This 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() can take an optional third argument: an index position within the string to start the search.

Here ’ s an example:

$myString = “Hello, world!”;

echo strpos( $myString, “o” ) . “ < br/ > ”;                 // Displays ‘4’

echo strpos( $myString, “o”, 5 ) . “ < br/ > ”;           // Displays ‘8’

 

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’

 

Finding the Number of Occurrences with 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’

 Third argument to specify the index position to start searching

Fourth argument to indicate how many characters the function should search before giving up.

$myString = “I say, nay, nay, and thrice nay!”;

echo substr_count( $myString, “nay”, 9 ) . “ <br/> ”;        // Displays ‘2’

echo substr_count( $myString, “nay”, 9, 6 ) . “ <br/> ”;    // Displays ‘1’

 

Searching for a Set of Characters with strpbrk()

If you need to find out if a string contains any one of a set of characters. 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

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 );

 If you want to know how many times the search string was replaced, pass in a variable as an optional fourth argument. After the function runs, this variable holds the number of replacements:

$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, $num ) . “ <br/> ”;

echo “The text was replaced $num times. <br/> ”;                        // Displays “The text was replaced 2 times.”

 

Replacing a Portion of a String with substr_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,”;

echo substr_replace( $myString, “bananas”, 11 ) . “ <br/> ”;       // Displays “It was the bananas”

 You can see that the preceding code has replaced all of the original text from the character at index 11 onwards with the replacement text ( “bananas” ).

 If you don ’ t want to replace all the text from the start point to the end of the string, you can specify an optional fourth argument containing the number of characters to replace:

$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 times,”

echo substr_replace( $myString, “bananas”, 19, 5 ) . “ <br/> ”;

 Pass a negative fourth argument to replace up to that many characters from the end of the string:

$myString = “It was the best of times, it was the worst of times,”;

// Displays “It was the best of bananas the worst of times,”

echo substr_replace( $myString, “bananas”, 19, -20 ) . “ <br/> ”;

You can also pass a zero value to insert the replacement text into the string rather than replacing characters:

$myString = “It was the best of times, it was the worst of times,”;

// Displays “It really was the best of times, it was the worst of times,”

echo substr_replace( $myString, “really “, 3, 0 ) . “ < br/ > ”;

 

Translating Characters with strtr()

This function used to  replace certain characters in a string with certain other characters. This 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.

 

$myString = “Here’s a little string”;

echo strtr( $myString, “ ‘”, “+-” ) . “ <br/> ”;         // Displays “Here-s+a+little+string”

 

Dealing with Upper - and Lowercase

To convert a string to all lowercase, use strtolower() . This function takes a string to convert, and returns a converted copy of the string:

$myString = “Hello, world!”;

echo strtolower( $myString );                        // Displays ‘hello, world!’

 

Similarly, you can use strtoupper() to convert a string to all uppercase:

$myString = “Hello, world!”;

echo strtoupper( $myString );                       // Displays ‘HELLO, WORLD!’

 

ucfirst() makes just the first letter of a string uppercase:

$myString = “hello, world!”;

echo ucfirst( $myString );                              // Displays ‘Hello, world!’

 

lcfirst() makes the first letter of a string lowercase:

$myString = “Hello, World!”;

echo lcfirst( $myString );                               // Displays ‘hello, World!’

 

ucwords() makes the first letter of each word in a string uppercase:

$myString = “hello, world!”;

echo ucwords( $myString );                          // Displays ‘Hello, World!’

However, PHP includes case - insensitive versions of many string functions, which means they ’ ll work even if the case of the strings don ’ t match. For example, there ’ s a case - insensitive version of strstr() ,  called stristr() :

$myString = “Hello, world!”;

// Displays “Found”

if ( stristr( $myString, “hello” ) )

echo “Found”;

else

echo “Not found”;

 

Formatting Strings

PHP gives you a number of functions that you can use to format strings in ways that are more human - friendly.

 General - Purpose Formatting with printf() and sprintf()

printf() takes a string argument called a format string , usually followed by one or more additional arguments containing the string or strings to format. It then outputs the result.

The format string contains ordinary text intermingled with one or more conversion specifications . Conversion specifications always start with a percent ( % ) symbol.

 Example

printf( “Pi rounded to a whole number is: %d”, M_PI ); //Displays “Pi rounded to a whole number is: 3”

or

Here ’ s another example that uses multiple conversion specifications:

// Displays “2 times 3 is 6.”

printf( “%d times %d is %d.”, 2, 3, 2*3 );

This code displays three decimal numbers within the output string: 2 , 3 , and the result of the expression 2*3 .

 

Using Type Specifiers

The d within the conversion specification, “%d” , is called a type specifier ; it tells printf() to format the argument as a decimal integer.

<html>

<head>

<title> Type Specifiers in Action </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/>

</head>

<body>

<h1> Type Specifiers in Action </h1>

<?php

$myNumber = 123.45;

printf( “Binary: %b <br/> ”, $myNumber );

printf( “Character: %c <br/> ”, $myNumber );

printf( “Decimal: %d <br/> ”, $myNumber );

printf( “Scientific: %e <br/> ”, $myNumber );

printf( “Float: %f <br/> ”, $myNumber );

printf( “Octal: %o <br/> ”, $myNumber );

printf( “String: %s <br/> ”, $myNumber );

printf( “Hex (lower case): %x < br/ > ”, $myNumber );

printf( “Hex (upper case): %X < br/ > ”, $myNumber );

?>

</body>

</html>

 








Specifying Signs

By default, printf() displays negative numbers with a minus (-) symbol in front of them, but doesn ’ t put a plus (+) symbol in front of positive numbers. To change printf() ’ s behavior so that it always displays a sign symbol, use the sign specifier , + , in front of the type specifier. Here ’ s an example:

 

printf( “%d <br/> ”, 123 );               // Displays “123”

printf( “%d <br/> ”, -123 );              // Displays “-123”

printf( “%+d <br/> ”, 123 );             // Displays “+123”

printf( “%+d <br/> ”, -123 );                       // Displays “-123”

 

Padding the Output

You can add characters to the left (by default) or the right of the formatted argument in order to pad it out to a fixed width. This is useful if you want to add leading zeros to a number, or horizontally align many strings by padding with spaces.

For example, the following code displays various numbers, using leading zeros where necessary to ensure the result is always six digits long:

printf( “%06d <br/ > ”, 123 ); // Displays “000123”

printf( “%06d <br/ > ”, 4567 ); // Displays “004567”

printf( “%06d <br/ > ”, 123456 ); // Displays “123456”

 

This example pads various strings using leading spaces to ensure that they ’ re right - aligned:

print “ <pre > ”;

printf( “%15s\n”, “Hi” );

printf( “%15s\n”, “Hello” );

printf( “%15s\n”, “Hello, world!” );

print “ </pre> ”;

Here ’ s the result:

      Hi

Hello

Hello, world!

To use your own padding character, insert an apostrophe ( ‘ ) followed by the character instead of the zero or space:

printf( “%’#8s”, “Hi” );      // Displays “######Hi”

If you want to add padding to the right rather than the left — so that the result is left - aligned rather than right - aligned — add a minus ( – ) symbol between the padding character and the width specifier:

printf( “%’#-8s”, “Hi” );      // Displays “Hi######”

Specifying Number Precision

When displaying floating - point numbers with the f or F type specifier, you can use a precision specifier to indicate how many decimal places to round the number to.

printf( “%.2f <br/> ”, 123.4567 );    // Displays “123.46”

You can use a padding specifier with a precision specifier,

printf( “%12.4f <br/> ”, 123.4567 ); // Displays “     123.4567”

By the way, if you use a precision specifier when formatting a string, printf() truncates the string to that many characters:

printf( “%.8s\n”, “Hello, world!” );             // Displays “Hello, w”

 

Trimming Strings with trim(), ltrim(), and rtrim()

·         trim() removes white space from the beginning and end of a string

·         ltrim() removes white space only from the beginning of a string

·         rtrim() removes white space only from the end of a string

 

$myString = “      What a lot of space!         “;

echo “ < pre > ”;

echo “|” . trim( $myString ) . “|\n”;           // Displays “|What a lot of space!|”

echo “|” . ltrim( $myString ) . “|\n”;          // Displays “|What a lot of space!              |”;

echo “|” . rtrim( $myString ) . “|\n”;         //        Displays “|       What a lot of space!|”;

echo “ </pre> ”;

 

Padding Strings with str_ pad()

To use str_pad() , pass the string to be padded, and the desired width of the final string. The function returns the string padded on the right using space characters (by default):

echo ‘ <pre> ”’;

echo str_pad( “Hello, world!”, 20 );                                                 // Displays “Hello, world!           

echo ‘” </pre> ’;

 

Wrapping Lines of Text with wordwrap()

PHP ’ s wordwrap() function takes a single - line string of text and splits it into several lines using newline ( “\n” ) characters, wrapping the lines at the ends of words to avoid splitting words. To use it, pass the string to wrap, and the function returns the wrapped string:

 

$myString = “But think not that this famous town has only harpooneers,

cannibals, and bumpkins to show her visitors. Not at all. Still New Bedford

is a queer place. Had it not been for us whalemen, that tract of land would

this day perhaps have been in as howling condition as the coast of

Labrador.”;

 

echo “ < pre > ”;

echo wordwrap( $myString );

echo “ < /pre > ”;

 

Formatting Numbers with number_format()

PHP ’ s number_format() function gives you a convenient way to format numbers in an easy - to – read way, with thousands separators and rounded to a specified number of decimal places.

echo number_format( 1234567.89 );                                        // Displays “1,234,568”

Prev Topic                                                                                          Next Topic Arrays

No comments:

Post a Comment