Class 5 - PHP Strings

of 36 /36
PHP Strings

Embed Size (px)

Transcript of Class 5 - PHP Strings

  • PHP Strings

    ****

  • Outline

    ****

  • What are Strings ?A string is a series of characters.Can contain any arbitrary number of characters, the only limit is the memory limit.

    ****

  • Ways To Write a String

    ****

  • Escaping characters

    Escaping is done using the backslash \ character :

    $x = He said \Im a developer\ ;

    $e = He said I\m a developer ;

    $d = $z ; // $d has the value of the variable $z

    $r = \$z ; // r has the value: $z

    ****

  • Special characters

    The most frequently used special characters we have are :

    \n : linefeed \t : the tab ( a number of spaces )

    We can only output these characters in double quoted and heredoc strings.

    echo Hi\n PHP; // prints Hi then PHP in the next line

    echo Hi \n PHP;// prints Hi \n PHP

    ****

  • Curly syntax

    In double quoted and heredoc strings, you can have the following :

    $x[10] = great;$x[name] = strings;

    $y = This is {$x[10]} ; // This is great$z = {$x[name]} are flexible.; // strings are flexible.

    ****

  • Accessing charactersStrings can be accessed like arrays to get a specific character :

    $x = String;

    echo $x[0]; // Secho $x[1];// techo $x[2];// r

    ****

  • String OperationsConcatenation operator .:

    $x = Hello . world; // Hello world

    Concatenating assignment operator :

    $x = Hello ;$x .= world // Hello world

    ****

  • String ComparisonCan compare strings using == operator :

    if( $x == Hi )echo yes;

    Can use strcmp() built-in function :

    if( strcmp( $x, Hi) == 0 )echo yes;

    Use strcasecmp() for case insensitive comparisons :

    if( strcasecmp( hi, Hi) == 0 )echo yes;

    ****

  • String LengthThe function strlen() returns the length of the string:

    Example:

    echo strlen( A string ); // 8

    ****

  • Searching Stringsint strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

    Returns the numeric position of the first occurrence of needle in the haystack string.

    Example:

    $mystring = 'abc';$findme = 'a';$pos = strpos($mystring, $findme); // 0

    ****

  • Replacing Stringsmixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

    This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

    Example:

    echo str_replace( Hi, Hello, Hi strings. ); // Hello strings.

    ****

  • Extracting Stringsstring substr ( string $string , int $start [, int $length ] )

    Returns the portion of string specified by the start and length parameters.

    Example :

    echo substr('abcdef', 1); // bcdef echo substr('abcdef', 1, 3); // bcdecho substr('abcdef', 0, 4); // abcdecho substr('abcdef', 0, 8); // abcdefecho substr('abcdef', -1, 1); // f

    ****

  • Splitting Stringsarray explode ( string $delimiter , string $string [, int $limit ])

    Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

    Example :

    $string = this is a string";$pieces = explode(" ", $string);var_dump($pieces); // prints an array containing the parts

    ****

  • Joining Stringsstring implode ( string $glue , array $pieces )

    Join array elements with a glue string.

    Example :

    $array = array( this, is, a, string );$string= implode(" ", $array);echo $string; // this is a string

    ****

  • ExerciseWrite a PHP function that reverses the string words, so If we have a string like this :

    this is the php strings lesson

    The function should return this :

    lesson strings php the is this

    ****

  • Exercise solution

    ****

  • Formatting Stringsstring number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

    This function formats a number according to the passed arguments.Example :

    $number = 1234.5678;

    $english_format_number = number_format($number, 2, '.', ''); // 1234.57

    ****

  • Formatting Stringsstring sprintf ( string $format [, mixed $args [, mixed $... ]] )

    Returns a string produced according to the formatting string format.

    Exampleprintf(My name is %s and my age is %d", John, 20 ); // My name is John and my age is 20

    For a complete list of details, visit : http://php.net/manual/en/function.sprintf.php

    ****

  • Regular ExpressionsRegular expressions ( Regex ) provide flexible means for matching strings of text.

    For example :

    How can I check whether the user supplied a valid e-mail or not ?

    There should be something that tells :

    Is the string like some characters/digits then @ then some characters/digits then .com ??? Here comes the regex.

    ****

  • Meta CharactersMeta characters are characters the have some special meanings in the regex pattern.

    CharacterDescription\general escape character with several uses^assert start of subject (or line, in multiline mode)$assert end of subject (or line, in multiline mode).match any character except newline (by default)[start character class definition]End character class definition|start of alternative branch(Start of sub pattern)End of sub pattern

    ****

  • Meta Characters

    CharacterDescription?0 or 1*0 or more+1 or more{Start min/max number of occurrences }End min/max number of occurrences ^negate the class, but only if it is the first character-Character range

    ****

  • Character ClassesCharacter classes define the type of characters in the regex pattern.

    ClassDescription\d Matches any numeric character - same as [0-9]\D Matches any non-numeric character - same as [^0-9]\s Matches any whitespace character - same as [ \t\n\r\f\v]\S Matches any non-whitespace character - same as [^ \t\n\r\f\v]\w Matches any alphanumeric character - same as [a-zA-Z0-9_]\W Matches any non-alphanumeric character - same as [^a-zA-Z0-9_]

    ****

  • Regex Examples

    Regular expression (pattern)Match (Subject )Not match CommentworldHello worldHello JimMatch if the pattern is present anywhere in the subject^worldworld classHello worldMatch if the pattern is present at the beginning of the subjectworld$Hello worldworld classMatch if the pattern is present at the end of the subject/world/iThis WoRLdHello JimMakes a search in case insensitive mode^world$worldHello worldThe string contains only the "world"world*worl, world, worldddworThere is 0 or more "d" after "worl"world+world, worldddworlThere is at least 1 "d" after "worl"

    ****

  • Regex Examples

    Regular expression (pattern)Match (Subject )Not match Commentworld?worl, world, worlywor, woryThere is 0 or 1 "d" after "worl"world{1}worldworlyThere is 1 "d" after "worl"world{1,}world, worldddworlyThere is 1 ore more "d" after "worl"world{2,3}worldd, worldddworldThere are 2 or 3 "d" after "worl"wo(rld)*wo, world, worldoldwaThere is 0 or more "rld" after "wo"earth|worldearth, worldsunThe string contains the "earth" or the "world"

    ****

  • Regex Examples

    Regular expression (pattern)Match (Subject )Not match Commentw.rldworld, wwrldwrldAny character in place of the dot.^.{5}$world, earthsunA string with exactly 5 characters[abc]abc, bbacccsunThere is an "a" or "b" or "c" in the string[a-z]worldWORLDThere are any lowercase letter in the string[a-zA-Z]world, WORLD, Worl12123There are any lower- or uppercase letter in the string[^wW]earthw, WThe actual character can not be a "w" or "W"

    ****

  • Regex Functionsint preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

    Searches subject for a match to the regular expression given in pattern. It will stop by the first occurrence of the pattern.

    Example:$x = preg_match( /php*/, phpppp, $result ); // returns 1var_dump($result); // array(1) { [0]=> string(6) "phpppp" }

    ****

  • Regex Functionsint preg_match_all ( string $pattern , string $subject , array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]] )

    Searches subject for a match to the regular expression given in pattern. It gets all the occurrences of the pattern in the string.

    Example:$x = preg_match_all( /php/, phpp phpzz, $result ); // returns 1

    var_dump($result); // array(1) { [0]=> array(2) { [0]=> string(3) "php" [1]=> string(3) "php" } }

    ****

  • Regex Functionsmixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

    Searches subject for matches to pattern and replaces them with replacement.

    Example:$x = preg_replace( /php*/, hi ,phpp phppz);

    echo $x ; // hi hiz

    ****

  • Exercise Write a PHP snippet that checks whether the user has entered a valid email or not ( the email should end with a .com ).

    ****

  • Exercise Solution

    ****

  • More info about RegexFor more info about regular expressions, please visit :

    http://www.php.net/manual/en/reference.pcre.pattern.syntax.php

    ****

  • Assignment1- Write a function that calculates the number of the words a string has.

    2- Write a PHP script that matches the following phone numbers :

    718 498 1043718 198-1043

    ****

  • What's Next?Web Programming.

    ****

  • Questions?

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****

    ****