Quick Contact

    Formatting, Joining, splitting, comparing strings
    Sprintf() Function

    The sprintf() function writes a formatted string to a variable.

    The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works “step-by-step”. At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

    Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and “\$”. See example two.

    Syntax

    sprintf(format,arg1,arg2,arg++)
    Parameter Description
    format

    Required. Specifies the string and how to format the variables in it.

    Possible format values:

    • %% – Returns a percent sign
    • %b – Binary number
    • %c – The character according to the ASCII value
    • %d – Signed decimal number (negative, zero or positive)
    • %e – Scientific notation using a lowercase (e.g. 1.2e+2)
    • %E – Scientific notation using a uppercase (e.g. 1.2E+2)
    • %u – Unsigned decimal number (equal to or greather than zero)
    • %f – Floating-point number (local settings aware)
    • %F – Floating-point number (not local settings aware)
    • %g – shorter of %e and %f
    • %G – shorter of %E and %f
    • %o – Octal number
    • %s – String
    • %x – Hexadecimal number (lowercase letters)
    • %X – Hexadecimal number (uppercase letters)

    Additional format values. These are placed between the % and the letter (example %.2f):

    • + (Forces both + and – in front of numbers. By default, only negative numbers are marked)
    • ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %’x20s (this uses “x” as padding)
    • – (Left-justifies the variable value)
    • [0-9] (Specifies the minimum width held of to the variable value)
    • .[0-9] (Specifies the number of decimal digits or maximum string length)

    Note: If multiple additional format values are used, they must be in the same order as above.

    arg1 Required. The argument to be inserted at the first %-sign in the format string
    arg2 Optional. The argument to be inserted at the second %-sign in the format string
    arg++ Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

    Example

    A demonstration of all possible format values:

    <?php
    $num1 = 123456789;
    $num2 = -123456789;
    $char = 50; // The ASCII Character 50 is 2
    // Note: The format value "%%" returns a percent sign
    echo sprintf("%%b = %b",$num1)."<br>"; // Binary number
    echo sprintf("%%c = %c",$char)."<br>"; // The ASCII Character
    echo sprintf("%%d = %d",$num1)."<br>"; // Signed decimal number
    echo sprintf("%%d = %d",$num2)."<br>"; // Signed decimal number
    echo sprintf("%%e = %e",$num1)."<br>"; // Scientific notation (lowercase)
    echo sprintf("%%E = %E",$num1)."<br>"; // Scientific notation(uppercase)
    echo sprintf("%%u = %u",$num1)."<br>"; // Unsigned decimal number (positive)
    echo sprintf("%%u = %u",$num2)."<br>"; // Unsigned decimal number (negative)
    echo sprintf("%%f = %f",$num1)."<br>"; // Floating-point number (local settings aware)
    echo sprintf("%%F = %F",$num1)."<br>"; // Floating-point number (not local sett aware)
    echo sprintf("%%g = %g",$num1)."<br>"; // Shorter of %e and %f
    echo sprintf("%%G = %G",$num1)."<br>"; // Shorter of %E and %f
    echo sprintf("%%o = %o",$num1)."<br>"; // Octal number
    echo sprintf("%%s = %s",$num1)."<br>"; // String
    echo sprintf("%%x = %x",$num1)."<br>"; // Hexadecimal number (lowercase)
    echo sprintf("%%X = %X",$num1)."<br>"; // Hexadecimal number (uppercase)
    echo sprintf("%%+d = %+d",$num1)."<br>"; // Sign specifier (positive)
    echo sprintf("%%+d = %+d",$num2)."<br>"; // Sign specifier (negative)
    ?>
    
    join() Function

    The join() function returns a string from the elements of an array.

    The join() function is an alias of the implode() function.

    Note: The join() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.

    Note: The separator parameter of join() is optional. However, it is recommended to always use two parameters for backwards compatibility.

    Syntax

    join(separator,array)

    Example

    Join array elements with a string:

    <?php
    $arr = array('Hello','World!','Beautiful','Day!');
    echo join(" ",$arr);
    ?>
    
    Parameter Description
    separator Optional. Specifies what to put between the array elements. Default is “” (an empty string)
    array Required. The array to join to a string
    str_split() Function

    The str_split() function splits a string into an array.

    Syntax

    str_split(string,length)

    Example

    Split the string “Hello” into an array:

    <?php
    print_r(str_split("Hello"));
    ?>
    

    Output

    Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
    Parameter Description
    string Required. Specifies the string to split
    length Optional. Specifies the length of each array element. Default is 1
    strcmp() Function

    The strcmp() function compares two strings.

    Note: The strcmp() function is binary-safe and case-sensitive.

    Syntax

    strcmp(string1,string2)

    Example

    Compare two strings (case-sensitive):

    <?php
    echo strcmp("Hello world!","Hello world!");
    ?>
    

    Output

    0
    //If this function returns 0, the two strings are equal.
     
    Parameter Description
    string1 Required. Specifies the first string to compare
    string2 Required. Specifies the second string to compare
    Introducing Regular Expression

    Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

    Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

    PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.

    • POSIX Regular Expressions
    • PERL Style Regular Expressions
    REGEX Implementation.
    POSIX Regular Expressions

    The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.

    The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.

    Lets give explanation for few concepts being used in POSIX regular expression. After that we will introduce you with regular expression related functions.

    Brackets

    Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

    Sr.No Expression & Description
    1

    [0-9]

    It matches any decimal digit from 0 through 9.

    2

    [a-z]

    It matches any character from lower-case a through lowercase z.

    3

    [A-Z]

    It matches any character from uppercase A through uppercase Z.

    4

    [a-Z]

    It matches any character from lowercase a through uppercase Z.

    The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

    Quantifiers

    The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.

    Sr.No Expression & Description
    1

    p+

    It matches any string containing at least one p.

    2

    p*

    It matches any string containing zero or more p’s.

    3

    p?

    It matches any string containing zero or one p’s.

    4

    p{N}

    p{N}It matches any string containing a sequence of N p’s

    5

    p{2,3}

    It matches any string containing a sequence of two or three p’s.

    6

    p{2, }

    It matches any string containing a sequence of at least two p’s.

    7

    p$

    It matches any string with p at the end of it.

    8

    ^p

    It matches any string with p at the beginning of it.

    Examples

    Following examples will clear your concepts about matching characters.

    Sr.No Expression & Description
    1

    [^a-zA-Z]

    It matches any string not containing any of the characters ranging from a through z and A through Z.

    2

    p.p

    It matches any string containing p, followed by any character, in turn followed by another p.

    3

    ^.{2}$

    It matches any string containing exactly two characters.

    4

    <b>(.*)</b>

    It matches any string enclosed within <b> and </b>.

    5

    p(hp)*

    It matches any string containing a p followed by zero or more instances of the sequence php.

    Regexp POSIX Functions

    PHP currently offers seven functions for searching strings using POSIX-style regular expressions –

    Sr.No Function & Description
    1

    ereg()

    The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.

    2

    ereg_replace()

    The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.

    3

    eregi()

    The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.

    4

    eregi_replace()

    The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.

    5

    split()

    The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.

    6

    spliti()

    The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.

    7

    sql_regcase()

    The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.

    PERL Style Regular Expressions

    Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.

    Lets give explanation for few concepts being used in PERL regular expressions. After that we will introduce you wih regular expression related functions.

    Meta Characters

    A meta character is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.

    For instance, you can search for large money sums using the ‘\d’ meta character: /([\d]+)000/, Here \d will search for any string of numerical character.

    Following is the list of meta characters which can be used in PERL Style Regular Expressions.

    Character Description
    . a single character
    \s a whitespace character (space, tab, newline)
    \S non-whitespace character
    \d a digit (0-9)
    \D a non-digit
    \w a word character (a-z, A-Z, 0-9, _)
    \W a non-word character
    [aeiou] matches a single character in the given set
    [^aeiou] matches a single character outside the given set
    (foo|bar|baz) matches any of the alternatives specified
    Modifiers

    Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.

    Modifier Description
    i Makes the match case insensitive
    m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary
    o Evaluates the expression only once
    s Allows use of . to match a newline character
    x Allows you to use white space in the expression for clarity
    g Globally finds all matches
    cg Allows a search to continue even after a global match fails
    Regexp PERL Compatible Functions

    PHP offers following functions for searching strings using Perl-compatible regular expressions –

    Sr.No Function & Description
    1

    preg_match()

    The preg_match() function searches strin

    +-*-**g for pattern, returning true if pattern exists, and false otherwise.

    2

    preg_match_all()

    The preg_match_all() function matches all occurrences of pattern in string.

    3

    preg_replace()

    The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.

    4

    preg_split()

    The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.

    5

    preg_grep()

    The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.

    6

    preg_ quote()

    Quote regular expression characters

    Summary

    The points summarizes the topic above:

    • The sprintf() function writes a formatted string to a variable.
    • The join() function is an alias of the implode() function.
    • The strcmp() function is binary-safe and case-sensitive.
    • Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.
    • The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions.

    Enrolled Yourself In Live Training – PHP Training

    Copyright 1999- Ducat Creative, All rights reserved.