Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu PHP and MySQL by Example- P4 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.62 MB, 50 trang )

Figure 6.6. Precision of numbers. Output from Example 6.6.


In the next example, printf() will format a string and a number.
Example 6.7.
<?php
$product_name = "Black shoes";
$product_price= 249.95;
1 printf( "Product %s will cost %6.2f dollars",

$product_name, $product_price );
?>
Explanation
! "#$%30,*(0+%)*(',/%30,*.',)%*:0%&0(<.*%)6$3'&'$()8%
%s
%.,-%
%6.2d
4%"#$%1.('.2+$%
$product_name
8%*#$%&'()*%.(/7<$,*8%:'++%2$%6(',*$-%.330(-',/%*0%*#$%&'()*%
&0(<.*%)6$3'&'$(8%
%s
8%.%)*(',/4%"#$%)$30,-%.(/7<$,*8%
$product_price
8%:'++%2$%
6(',*$-%.330(-',/%*0%*#$%)$30,-%&0(<.*%)6$3'&'$(8%
%6.2f
4%I,%*#')%3.)$8%
6
%($&$()%*0%
*0*.+%,7<2$(%0&%-'/'*)%*#.*%*#')%,7<2$(%3.,%03376=%.,-%


.2
%)6$3&''$)%.%6($3')'0,%
0&%5%6+.3$)%*0%*#$%('/#*%0&%*#$%-$3'<.+%60',*4%I&%*#$%,7<2$(%')%+.(/$(%*#.,%D8%
printf()
%:'++%,0*%*(7,3.*$%'*4%I*%R7)*%<'/#*%,0*%+00A%*#$%:.=%=07%#.-%
$,1')'0,$-%'*4%B$$%C'/7($%D4Z4
%









Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 6.7. Output from Example 6.7.


Table 6.2 shows the most common format specifiers.
The format specifier can be modified by placing specifying a precision, left or right justification, padding characters,
and so on, as shown in Table 6.3.
Table 6.3. Modifiers for the printf() Format Specifier
Modifier Example Format
.

%.2f

B6$3'&'$)%.%6($3')'0,%0&%*:0%-'/'*)%*0%*#$%('/#*%0&%*#$%-$3'<.+%60',*%',%

.%&+0.*',/O60',*%,7<2$(
integer

%8d

B6$3'&'$)%,7<2$(%0&%3#.(.3*$()%&0(%*#')%.(/7<$,*%*0%2$%-')6+.=$-@%
$4/48%&'$+-%:'-*#%0&%[%-'/'*)
-

%-8.2f
%
%-
30s

S.7)$)%*#$%&0(<.**',/%*0%2$%+$&*%R7)*'&'$-@%$4/48%+$&*OR7)*'&'$-%&+0.*',/O
60',*%,7<2$(%:'*#%.%&'$+-%:'-*#%0&%[8%0(%+$&*OR7)*'&'$-%P\O)6.3$%)*(',/
0

%08d

F.-)%*#$%,7<2$(%:'*#%\)
%
There are some other formatting functions similar to the printf function differing primarily in how the output is
displayed.
The sprintf() Function
This function is identical to printf() except that instead of displaying the formatted string, sprintf() returns the
formatted string so that you can assign it to a variable. See Example 6.8.
Format
string sprintf ( string format [, mixed args [, mixed ...]] )
%

Example:
$formatted_string=sprintf("%s owes me %.2f dollars\n",
$name, $amount);

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 6.8.
<?php
$product_name = "Purple Dress";
$product_price = 199.95;
1 $output = sprintf( "Product <b>%s</b> will cost <u>$%6.2f</u> +

tax", $product_name, $product_price );
?>
<html><title>The sprintf() Function</title></head>
<body bgcolor="#EBF4F3">
<h1>Shopping Cart Checkout</h1>
<font face="Arial">
2 <?= $output ?>
</font></body>
Explanation
! "#$%&'()*%6.(.<$*$(%*0%*#$%
sprintf()
%&7,3*'0,%')%*#$%30,*(0+%)*(',/%)6$3'&=',/%
#0:%*0%6(',*%*#$%)*(',/4%"#$%*:0%.(/7<$,*)%&0++0:',/%*#$%30,*(0+%)*(',/%.($%*#$%
.3*7.+%1.('.2+$)8%
$product_name
%.,-%
$product_price
8%*#.*%30(($)60,-%*0%$.3#%
0&%*#$%&0(<.*%30,1$()'0,%)6$3'&'$()8%

%s
%.,-%
%6.2f
8%',%*7(,4%"#$%
sprintf()
%
&7,3*'0,%:'++%&0(<.*%*#$%)*(',/%.,-%.))'/,%'*%*0%*#$%1.('.2+$8%3.++$-%
$output
variable
4
5 G$($%:$%7)$%*#$%)#0(*%&0(<%*0%6(',*%07*%.%1.+7$%0&%*#$%1.('.2+$%
$output
%',*0%*#$%
G"]^%2(0:)$(8%.)%)#0:,%',%C'/7($%D4[4
%
Figure 6.8. The sprintf() function. Output from Example 6.8.




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The fprintf() Function
Whereas the printf() function writes the output to the standard output stream (the browser), the fprintf()
function sends the output to any output stream specified, usually a file.
Format
int fprintf ( resource handle, string format [, mixed args [,
mixed ...]] )
%
Example:
sprintf($filehandle, "%04d-%02d-%02d", $year, $month, $day);


For more information on streams and files, see Chapter 11, “Files and Directories.”
6.2.2. Formatting Numbers and Money
Putting commas or spaces in numbers or printing out the dollar value of money causes a number to become a string and
can be handled with printf(). PHP also provides two special functions, the number_format() function and the
money_format() function.
The number_format() Function
PHP provides the number_format() function to format a number with grouped thousands. There are three ways to
use this function. You can specify no arguments, two arguments, or four arguments, but not three arguments.
When only one number is specified, the number returned will be a whole number. It will include commas for every
group of thousands, but the fractional part will be truncated along with the decimal point. If the first number after the
decimal point is 5 or higher, the new number will be rounded up.
If two numbers are specified, the second number will indicate the number of decimal places to format, such as two
places after the decimal point for a dollar and cents amount. Groups of thousands will still be comma-separated.
The third way to use this function is to specify the number to format, number of decimal places, as well as the
characters to use for separating groups of thousands, as well as the decimal point. This is useful for locales that use
number formats different than North American formats.
Example 6.9 illustrates how to use the number_format() function. Figure 6.9 shows the output, three formatted
numbers.
Format
string number_format ( float number [, int decimals [,
string dec_point, string thousands_sep]] )
%
Example:
$number=123456.5456 $new_string = number_format($number); // Returns: 123,457
$new_string = number_format($number, 2); // Returns: 123,456.55 $num_francais =
number_format($number, 2, ',', ' '); // Returns 1 234,56

Example 6.9.
<?php

$number = 7634.887;
// American format is the default: 7,643.89
1
$us_format = number_format($number, 2);
print "$us_format<br />";

// French format: 7 634,89
2
$french_format = number_format($number, 2, ',', ' ');
print "$french_format<br />";

// American format without thousands separator: 7634.89
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3
$us_format2 = number_format($number, 2, '.', '');
print "$us_format2<br />";

?>
Explanation
! "#')%')%*#$%-$&.7+*%&0(<.*%&0(%*#$%X4B4%,7<2$()4%"#$%)$30,-%6.(.<$*$(%)6$3'&'$)%
*#$%,7<2$(%0&%-$3'<.+%6+.3$)8%',%*#')%3.)$%*:04%
number_format()
%.7*0<.*'3.++=%
(07,-)%*0%*:0%-$3'<.+)%',%*#')%3.)$4
5 "#')%+',$%)#0:)%#0:%*0%7)$%*#$%
number_format()
%&7,3*'0,%:'*#%&07(%
.(/7<$,*)4%"#$%&'()*%*:0%.(/7<$,*)%.($%*#$%).<$%.)%',%*#$%6($1'07)%+',$E%*#$%
,7<2$(%*0%2$%&0(<.**$-%.,-%*#$%,7<2$(%0&%-$3'<.+%6+.3$)4%"#$%*#'(-%
.(/7<$,*%)6$3'&'$)%*#$%)$6.(.*0(%3#.(.3*$(%*0%2$%7)$-%&0(%-$3'<.+%6+.3$)4%I,%

C(.,3$8%.%30<<.%')%7)$-%(.*#$(%*#.,%.%-$3'<.+%60',*4%"#$%&07(*#%.(/7<$,*%')%
*#$%)$6.(.*0(%&0(%*#$%*#07).,-)%.,-%#$($%:$%7)$%.%)',/+$%)6.3$8%(.*#$(%*#.,%.%
30<<.8%*#$%*#07).,-)%)$6.(.*0(%30<<0,+=%7)$-%',%<0)*%_7(06$.,%307,*('$)4
P "#')%$9.<6+$%')%1$(=%)'<'+.(%*0%*#$%6($1'07)%0,$4%"#$%<.',%-'&&$($,3$%')%*#.*%
*#$%&07(*#%.(/7<$,*%')%$<6*=8%)6$3'&=',/%,0%3#.(.3*$(%&0(%*#$%*#07).,-)%
)$6.(.*0(4

Figure 6.9. The number_format() function. The output from Example 6.9.

%
The money_format() Function
The money_format() function formats a number as a string representing currency. Because this function depends
on a C library function called strfmon(), it cannot be implemented on your system if you are using Windows. This
function can format money for any number of locales and comes with a large array of formatting specifications. It
works with negative numbers, deals with left and right precision, padding, and so on, similar to the printf()
function. For a complete discussion on how to use this function, see the PHP manual.


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
string money_format ( string format, float number )
%
Example:
setlocale(LC_MONETARY, 'en_US'); echo money_format('%i', $number) . "\n"; // USD
1,234.56

6.2.3. Finding the Length of a String
The strlen() Function
To find the length of a string (how many characters there are in the string), PHP provides the strlen() function. See
Example 6.10.

Format
int strlen ( string string )
%
Example:
$length = strlen("Hello, world\n");

Example 6.10.
<html><head><title>Finding the Length of a String</title>
</head>
<body bgcolor="lightgreen">
<font size="+1">
<?php
1 $string="\t\tHello, world.";
2 $length=strlen($string);
print nl2br("There are $length characters in \"$string\"");
?>
</body>
</html>
Explanation
! "#$%1.('.2+$8%
$string
8%30,*.',)%.%)*(',/%0&%3#.(.3*$()%',3+7-',/%*#$%*.2%3#.(.3*$(4
5 "#$%
strlen()
%&7,3*'0,%($*7(,)%*#$%,7<2$(%0&%3#.(.3*$()%',%
$string
4%"#$%*.2%3#.(.3*$(%
-0$),H*%)#0:%76%',%*#$%2(0:)$(8%27*%2=%1'$:',/%*#$%)07(3$%30-$8%=07%3.,%)$$%'*8%.)%)#0:,%
',%C'/7($%D4!\4
%

%
%
%
%
%
%
%
%
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
%
Figure 6.10. The strlen() function. Viewing the source code from Example 6.10.
%

6.2.4. Finding the Number of Words in a String
The str_word_count() Function
The str_word_count() function returns information about the words that make up a string. A word is defined as a
locale-dependent (Germany, U.S., etc.) string containing alphabetic characters, which also can contain, but not start
with ' and - characters. By default, the str_word_count() function counts the number of words in a string. An
optional third argument can be one of the three values shown in Table 6.4.
Table 6.4. Optional Third Arguments to the str_word_count() Function
Argument What+It+Returns
0

`$*7(,)%*#$%,7<2$(%0&%:0(-)%&07,-4
1

`$*7(,)%.,%.((.=%30,*.',',/%.++%*#$%:0(-)%&07,-%',)'-$%*#$%)*(',/4
2


`$*7(,)%.,%.))03'.*'1$%.((.=8%:#$($%*#$%A$=%')%*#$%,7<$('3%60)'*'0,%0&%*#$%:0(-%
',)'-$%*#$%)*(',/%.,-%*#$%1.+7$%')%*#$%.3*7.+%:0(-%'*)$+&4
%
An optional fourth argument, charlist, allows you to add characters that will be accepted as part of a word, such as
foreign accent marks, ellipses, long dashes, or hyphens.
Format
mixed str_word_count(string string [, int format [, string charlist]] )
%
Example:
$num_words = str_word_count("Happy New Year, to you!");
print_r(str_word_count("Solstickan såljes till förmån för barn och
gamla",1, "åÅö");

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
6.2.5. Changing the Case of Strings
If you are validating an e-mail address or the abbreviation for a state, such as CA or MD, you might want to convert the
entire string into lowercase letters before proceding, or you might want to convert just the first character in a string, as
in Mrs. or Dr. PHP provides functions for changing the case of the characters in a string, as shown in Table 6.5.
Table 6.5. Functions That Change the Case of Strings
Function What+It+Does
strtoupper()

S0,1$(*)%.%)*(',/%*0%766$(3.)$%+$**$()
strtolower()

S0,1$(*)%.%)*(',/%*0%+0:$(3.)$%+$**$()
ucfirst()

S0,1$(*)%*#$%&'()*%+$**$(%',%.%)*(',/%*0%766$(3.)$
ucwords()


S0,1$(*)%*#$%&'()*%+$**$(%',%$.3#%:0(-%0&%.%)*(',/%*0%766$(3.)$
mb_convert_case()

S0,1$(*)%3.)$%0&%.%)*(',/%2.)$-%0,%X,'30-$%3#.(.3*$(%6(06$(*'$)
%
The strtoupper() and strtolower() Functions
The functions strtoupper() and strtolower() are used to convert the case of characters in a string from upper-
to lowercase or vice versa. strtoupper() takes a string and returns a new string with every single letter capitalized.
strtolower() returns a new string with every character converted to lowercase.
Format
string strtoupper ( string ) string strtolower ( string )
%
Example:
$newstring=strtoupper("merry christmas"); // returns "MERRY CHRISTMAS"
$newstring=strtolower("HAPPY NEW YEAR"); // returns "happy new year"

Example 6.11.
<?php
$text = "";
1 print strtolower( $text . "<br />" ); //prints:

2 print strtoupper( $text . "<br />" ); //prints:

?>
Explanation
! "#')%+',$%:'++%R7)*%07*67*%*#$%*$9*%30,1$(*$-%.++%',%+0:$(3.)$4
5
strtoupper()
%-0$)%*#$%0660)'*$8%30,1$(*',/%*#$%*$9*%',*0%766$(3.)$%+$**$()4


The ucfirst() and ucwords() Functions
If you want to change just the first character in a string to uppercase, PHP provides the ucfirst() and ucwords()
functions. The ucfirst() function converts the first character of a string to uppercase. The ucwords() function
capitalizes first letters of all the words in the string.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
string ucfirst ( string str ) string ucword( string str)
%
Example:
// Returns "San jose, california" $newstring=ucfirst("san jose, california"); //
Returns "San Jose, California" $newstring=ucwords("san jose, california");

Example 6.12.
<?php
$text = "it rains in spain";
1 print ucfirst( $text . "<br />" ); // prints: It rains in spain
2 print ucwords( $text . "<br />" ); // prints: It Rains In Spain
?>
Explanation
! "#')%+',$%07*67*)%
It rains in spain
4%"#$%
ucfirst()
%&7,3*'0,%($*7(,)%*#$%
)*(',/%:'*#%*#$%&'()*%+$**$(%3.6'*'.+'a$-4%B$$%C'/7($%D4!!4
5 "#$%
ucwords()
%&7,3*'0,%3.6'*.+'a$)%*#$%&'()*%+$**$(%',%$.3#%:0(-%0&%*#$%)*(',/8%
+'A$%*#$%*'*+$%',%.%200A8%&0(%$9.<6+$4%"#$%07*67*%:'++%2$%

It Rains In Spain
8%.)%
)#0:,%',%C'/7($%D4!!4
%
Figure 6.11. The ucfirst() and ucwords() functions.


The mb_convert_case() Function
The mb_convert_case() function is like strtolower() and strtoupper() but is not locale dependent; that
is, it bases its conversion on Unicode characters rather than just ASCII, which means letters containing the German
umlaut, the Swedish ring, or French accent marks are folded (included) into case conversion. To specify the case, this
function provides three modes: MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE. You can also specify a
supported character set to establish how the string will be encoded.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.6. Supported Character Sets
Charset Aliases Description
IBUO[[bcO
!
IBU[[bcO! ?$)*$(,%_7(06$.,8%^.*',O!
IBUO[[bcO
!b
IBU[[bcO
!b
?$)*$(,%_7(06$.,8%^.*',Oc4%W--)%*#$%_7(0%)'/,8%C($,3#%.,-%C',,')#%
+$**$()%<'))',/%',%^.*',O!JIBUO[[bcO!K
X"CO[ % WBSII%30<6.*'2+$%<7+*'2=*$%[O2'*%X,'30-$
36[DD '2<[DD8%
[DD
VUBO)6$3'&'3%S=('++'3%3#.()$*@%)7660(*$-%',%Q4P45
%

Format
string mb_convert_case ( string str, int mode [, string encoding] )
%
Example:
$string = "exit here!!"; echo mb_convert_case($string, MB_CASE_UPPER,"UTF-8");
// Returns: EXIT HERE!! $string = "förvaras oåtkomligt för barn"; echo
mb_convert_case($string, MB_CASE_TITLE,"IS0-8859-15"); // Returns: Förvaras
Oåtkomligt För Barn

6.2.6. Comparing Strings
Does the password a user entered match the one on file? Does the user’s response compare to the expected answer?
PHP provides a number of functions to make comparing strings relatively easy.
To ensure you are always comparing strings, you should use string comparison functions rather than comparison
operators because the functions always cast their arguments to strings before comparing them. Also keep in mind when
comparing strings, that " hello"
[1]
is not the same as "hello" or "Hello", for example. PHP provides several
functions to compare two strings, listed in Table 6.7.
[1]
You can use the trim() function to remove unwanted whitespace (See “The trim() Functions—trim(), ltrim(), chop,
rtrim()” on page 182).
Table 6.7. Return Value from Comparison
Value What+It+Means
0
%Ja$(0K "#$%*:0%1.+7$)%.($%$;7.+
> 0
%J/($.*$(%*#.,%a$(0K T.+7$%*:0%')%/($.*$(%*#.,%1.+7$%0,$
< 0
%J+$))%*#.,%a$(0K T.+7$%0,$%')%/($.*$(%*#.,%1.+7$%*:0
%

All string comparisons take at least two arguments and return a value based on comparing those arguments. The return
value is always an integer that can be interpreted as shown in Table 6.7.
Table 6.8 lists string comparison functions and how they compare two strings.



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 6.8. String Comparison
Function What+It+Does
strcmp()

S0<6.($)%*:0%)*(',/)%J3.)$%)$,)'*'1$K
strcasecmp()

S0<6.($)%*:0%)*(',/)%J,0*%3.)$%)$,)'*'1$K
strnatcmp(str1, str2);

S0<6.($)%*:0%)*(',/)%',%WBSII%0(-$(8%27*%.,=%,7<2$()%.($%
30<6.($-%,7<$('3.++=
strnatcasecmp(str1,
str2);

S0<6.($)%*:0%)*(',/)%',%WBSII%0(-$(8%3.)$%',)$,)'*'1$8%,7<2$()%
.)%,7<2$()
strncasecomp()

S0<6.($)%*:0%)*(',/)%J,0*%3.)$%)$,)'*'1$K%.,-%.++0:)%=07%*0%
)6$3'&=%#0:%<.,=%3#.(.3*$()%*0%30<6.($
strspn()


S0<6.($)%.%)*(',/%./.',)*%3#.(.3*$()%($6($)$,*$-%2=%.%<.)A
strcspn()

S0<6.($)%.%)*(',/%*#.*%30,*.',)%3#.(.3*$()%,0*%',%*#$%<.)A
%
The strcmp() Function (Case Sensitive)
The strcmp() function is most often used to compare two strings.
Format
int strcmp ( string str1, string str2 )
%
Example:
$number = strcmp( "apples", "oranges");

The strcmp() function uses a lexicographical comparison algorithm to compare two strings, meaning it compares
each character in the string alphabetically based on the system’s collating sequence. Because PHP uses the ASCII
collating sequence, an uppercase “A” is represented as decimal 65 and an uppercase “B” as decimal 66, and so on. On
the other hand, a lowercase “a” is 97 and a lowercase “b” is 98, and so on. If you compare “A” to “a,” you can say that
“A” is less than “a” because of their numeric representation in the ASCII table; that is, 65 is less than 97.
The strcmp() function returns a number less than 0 if the first string is less than second string, a number greater than
0 if the first string is greater than the second string, and 0 if they are equal.
The strcmp() function is case sensitive meaning that “Dan” and “dan” are not the same. If you want to ignore the
case of the letters, use the strcasecmp() function discussed next. See Example 6.13 to see how the strcmp()
function works and its output in Figure 6.12.
Example 6.13.
S0-$%T'$:E%%
<html>
<head><title>The strcmp() Function</title></head>
<body bgcolor="lavendar">
<font face="verdana">
<pre>

<h3>Comparing Strings</h3>
<?php
$string1 = "Dan";
$string2 = "Daniel";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
1 print "strcmp( '$string1', '$string2' ) outputs " . strcmp(

$string1, $string2 );
2 print "\nstrcmp( '$string2', '$string2' ) outputs " .
strcmp(

$string2,$string2 );
3 print "\nstrcmp( '$string2', '$string1' ) outputs " .
strcmp(

$string2, $string1 );
4 print "\nstrcmp( 'dan', 'Dan' ) outputs " . strcmp(

'dan', 'Dan');
print "\nstrcmp( 'Dan', 'dan' ) outputs " . strcmp(

'Dan', 'dan');
?>
<pre>
</body>
</html>
Explanation
!
Dan
%')%+$9'0/(.6#'3.++=%)<.++$(%*#$,%

Daniel
8%($)7+*',/%',%.%,$/.*'1$%,7<2$(4
5
Daniel
%.,-%
Daniel
%.($%'-$,*'3.+8%*#7)%:$%/$*%a$(0%.)%*#$%($)7+*%0&%30<6.(')0,4
P
Daniel
%')%+.(/$(%*#$,%
Dan
8%($)7+*',/%',%.%60)'*'1$%,7<2$(4
Q "#$%
d
%',%
dan
%')%/($.*$(%*#.,%*#$%
D
%',%
Dan
8%.%60)'*'1$%,7<2$(4%B$$%C'/7($%D4!54
Figure 6.12. The strcmp() function. Output from Example 6.13.
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The strcasecmp() Function (Case Insensitive)
The strcasecmp() function works like the strcmp() function, but ignores the case of characters in strings; that is,
an uppercase “A” and a lowercase “a” are treated as equals when comparing characters.
The strcasecmp() function returns a number less than 0 if the first string is less than the second string, a number
greater than 0 if the first string is greater than the second string, and 0 if they are equal. Example 6.14 demonstrates how
the function works.

Format
int strcasecmp ( string str1, string str2 )
%
Example:
$number=strcasecmp("apples", "APples"); // Case-insensitive comparison

Example 6.14.
d<html><head><title>The strcasecmp() Function</title></head>
<body bgcolor="lightblue">
<h3>Comparing Strings--Case-Insensitive</h3>
<?php
1 $str1 = "new york";
$str2 = "New York";
2 if (strcasecmp($str1, $str2) == 0) {
print "<em>$str1</em> is equal to <em>$str2</em>.<br
/>";
}
?>
</body></html>
Explanation
! ":0%)*(',/%1.('.2+$)%.($%.))'/,$-%*#$%).<$%)*(',/8%0,+=%-'&&$(',/%',%3.)$4
5 "#$%
strcasecmp()
%&7,3*'0,%'/,0($)%*#$%-'&&$($,3$%',%3.)$%.,-%30<6.($)%*#$%3#.(.3*$()4%
"#$%)*(',/)%.($%$;7.+4%`$<$<2$(%*#.*%'&%*#$%($*7(,$-%1.+7$%
== 0
8%*#$%)*(',/)%.($%$;7.+4%
B$$%C'/7($%D4!P4
%
Figure 6.13. Case-insensitive string comparison.

%
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The strncasecmp() Function (Limits Character Length)
This strncasecmp() function is similar to strcasecmp() in that it also ignores the case of characters when
doing the comparison, but in addition, it lets you specify the (upper limit of the) number of characters (length) from
each string to be used in the comparison.
The strncasecmp() function returns a number less than 0 if the first string is less than the second string, a number
greater than 0 if the first string is greater than the second string, and 0 if they are equal. Example 6.15 demonstrates how
this function works.
Format
int strncasecmp ( string str1, string str2, int length )
%
Example:
// Compares first 4 characters in each string $number = strncasecmp("Homeland",
"homeland", 4);
Example 6.15.
<html><head><title>The strncasecmp() Function</title></head>
<body>
<h3>Comparing Strings by Limit of Characters</h3>
<?php
1 $str1="chronometer";
$str2="Chronology";
2 if ( strncasecmp($str1,$str2, 5)==0){
print "The first 5 characters of <em>$str1</em> are the
same as the first 5 characters in <em>$str2 </em><br
/>";
}
else{
print "They do not compare.<br />";

}
?>
</body>
</html>
Explanation
! ":0%)*(',/%1.('.2+$)%.($%.))'/,$-%*#$%).<$%)*(',/8%-'&&$(',/%0,+=%',%3.)$4
5 "#$%
strncasecmp()
%&7,3*'0,%'/,0($)%*#$%-'&&$($,3$%',%3.)$%.,-%30<6.($)%0,+=%
*#$%&'()*%b%3#.(.3*$()4%"#$%*#'(-%.(/7<$,*8%
5
8%)6$3'&'$)%#0:%<.,=%3#.(.3*$()%
=07%:.,*%*0%30<6.($%)*.(*',/%.*%*#$%2$/',,',/%0&%*#$%)*(',/4%"#$%)*(',/)%.($%
$;7.+4%B$$%C'/7($%D4!Q4
Figure 6.14. The strncasecmp() function.
%
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The strnatcmp() Function (Natural Order Comparison)
If you compare numeric strings, the expression '2' > '100' will evaluate to true because in the first position 2 is
greater than 1 when using the ASCII collating sequence. The other character positions are irrelevant because the first
string only has one character. The string comparison functions we have seen so far always cast their arguments to
strings before doing the comparison. The strnatcmp() function takes into consideration strings that contain
numbers. This function compares characters in two strings using the ASCII collating sequence, but if there are any
numbers within the string they are compared in natural order; that is, as numbers the way we think of numbers, where
100 is greater than 2. This is true even if the numbers occur in the middle of the string. Thus 'January 2' will
evaluate to less than 'January 10', whereas in a normal string comparison it would be greater since 2 is greater
than 1.
The strnatcasecmp() function is just like the strnatcmp() function except that it is not case insensitive when
comparing strings.
Format

int strnatcmp ( string str1, string str2 )
%
Example:
// Returns 1 -- string 2 > string 1 echo strnatcmp('January 2, 2006', 'January
10, 2006'); // Returns -1 -- string 1 > string 2 echo strcmp( 'January 2, 2006',
'January 10, 2006' );

The strspn() Function (Using a Mask for Comparison)
The strspn() function compares two strings and returns the number of characters that are contained in the initial part
of the first string that match a set of characters provided in the second string, called the mask. For example, if you want
to check that a password contains both digits and letters or if a zip code consists of only numbers, this function can be
used to check that specified characters are included in the string.
The two optional arguments allow you define where you want to start looking for the characters in the string and the
length of the string to compare. Example 6.16 demonstrates how to use the strspn() function.
Format
int strspn ( string str1, string str2 [, int start [, int length]] )
%
Example:
$year = "1953 was a very good year!"; $mask="0123456789"
$count=strspn($year,$mask,0,4); // The string must start with 4 digits

Example 6.16.
<html><head><title>The strspn() Function</title>
</head>
<body bgcolor="lavender">
<font size="+1">
<h3>Finding the Length of a String by a Mask</h3>
<?php
1 $mask = "0123456789";
2 $zip = "95926";

3 $count=strspn($zip,$mask);
4 if ($count == strlen($zip)){
print "The zip code consists of $count numbers.<br />";
}
?>
</body>
</html

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
!
$mask
%30,)')*)%0&%.%)*(',/%0&%,7<2$()%*#.*%:'++%)$(1$%.)%*#$%<.)A4
5 "#$%1.('.2+$8%
$zip
8%30,*.',)%,7<2$()4
P "#$%
strspn()
%&7,3*'0,%($*7(,)%*#$%,7<2$(%0&%3#.(.3*$()%',%
$zip
%*#.*%<.*3#%
*#$%3#.(.3*$()%',%*#$%<.)A4%"#$%
strspn()
%&7,3*'0,%)#07+-%($*7(,%.%307,*%0&%b8%
2$3.7)$%*#$($%.($%b%,7<2$()%',%
$zip
%.,-%*#$=%.($%.++%&07,-%',%*#$%<.)A%
1.('.2+$4
Q "#')%+',$%3#$3A)%'&%*#$%1.+7$%0&%
$count

%')%$;7.+%*0%*#$%,7<2$(%0&%3#.(.3*$()%',%
$zip
8%*#$%)*(',/%+$,/*#8%.,-%'&%)08%6(',*)%L"#$%a'6%30-$%30,)')*)%0&%b%,7<2$()4M

The strcspn() Function (Comparison Not Matching a Mask)
The strcspn() function is just like the strspn() function, but finds length of initial segment not matching the
mask; that is, it returns the length of the initial segment of the first string not containing any of the characters in the
second string. The strcspn() function accepts two optional integer parameters that can be used to define the start
position and the length of the string being compared.
Format
int strcspn ( string str1, string str2 [, int start [, int length]] )
%
Example:
$filename = "test3"; $length=strcspn("$filename", "1234567890", 0, 4); //
Returns 4; first 4 characters should not be numbers

6.2.7. Finding Similarities in Strings
The string comparison functions previously discussed perform alphanumeric string comparisons, but what if we want to
see if one string sounds or is pronounced like another or how and where the text differs in two strings? PHP provides a
set of functions to find similarities or differences in strings. These functions might be useful for programs that check
spelling, perform database searches, or any advanced text processing.
The soundex() and metaphone() Functions (Phonic Similarity)
Phonic similarity bases its comparison on whether or not two strings are homophones, that is, they sound alike. Words
such as “genes” and “jeans” or “morning” and “mourning” are homophones.
The soundex() and metaphone() functions take a string as an argument, and return a key. Soundex keys are short
alphanumeric representations of a word’s English pronounciation that can be used to compare the sound in strings. If
the keys are the same, then the words sound the same in English. After testing different words, you will see that these
functions base their comparison on American English pronounciation rather than British English. For example, “father”
and “farther” do not sound the same in America, nor do “source” and “sauce,” or “tuba” and “tuber.”
The only obvious difference between the two functions is that metaphone() is more precise in determining which

words have the same pronunciation. Example 6.17 demonstrates how to use the soundex() and metaphone()
functions. The output is diplayed in Figure 6.15.
Format
string soundex ( string str ) string metaphone ( string str [, int phones] )
%
Example:
$key1=soundex("bored"); $key2=soundex("board"); if ( $key1 == $key2 ){ echo "The
strings sound alike<br />";}




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 6.17.
S0-$%T'$:E%
<html><head><title>Words that Sound the Same</title>
</head>
<body bgcolor="silver">
<font size="+1">
<?php
1 $sound1 = "bald";
$sound2 = "bawled";
2 $key1=soundex("$sound1");

$key2=soundex("$sound2");
3 if ($key1 == $key2){
print "The key values are: $key1 and $key2.\n<br />";
print "\"$sound1\" and \"$sound2\" are homophones.\n<br
/>";
}

4 $sound1 = "tuba";
$sound2 = "tuber";
5 if (metaphone($sound1) == metaphone($sound2)){
print "\"$sound1\" and \"$sound2\" are homonyms.\n";
}
else{
print "\"$sound1\" and \"$sound2\" do not sound the
same.\n";
}
?>
</font>
</body>
</html>
Explanation
! "#$%*:0%1.('.2+$)8%
$string1
%.,-%
$string2
8%.($%.))'/,$-%)*(',/)%:#0)$%1.+7$)%)07,-%*#$%
).<$8%3.++$-%#0<06#0,$)4
5 "#$%A$=)%6(0-73$-%2=%*#$%
soundex()
%&7,3*'0,%.($%)#0:,%',%C'/7($%D4!b4%"#$=%.($%&07(%
3#.(.3*$(%)*(',/)8%:#'3#%3.,%2$%30<6.($-4
P I&%*#$%A$=)%.($%*#$%).<$8%*#$%:0(-)%.($%#0<06#0,$)4
Q ":0%<0($%#0<06#0,$)%.($%.))'/,$-%*0%
$sound1
%.,-%
$sound2
8%($)6$3*'1$+=4

b "#$%A$=)%($*7(,$-%&(0<%*#$%
metaphone()
%&7,3*'0,%.($%<0($%6($3')$%',%-$.+',/%:'*#%
_,/+')#%6(0,7,3'.*'0,4
%




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 6.15. Homophones—words that sound the same.


The similar_text() and levenshtein() Functions (Textual Similarity)
PHP provides two functions to test the similarity between the text in two strings. They are the similar_text() and
the levenshtein() functions.
The similar_text() function calculates the similarity of two strings and returns the number of characters that are
the same, allowing for additions, subtraction, and repetition. It also takes an optional third parameter, containing a value
that represents the percentage of similarity between the strings. Example 6.18 demonstrates how the
similar_text() function is used.
Format
int similar_text ( string first, string second [, float percent] )
%
Example:
$number_same = similar_text($a, $b, $percent);

Example 6.18.
<html><head><title>Text that is Similar</title>
</head><body bgcolor="silver">
<font size="+1">

<?php
1 $string1 = "Once upon a time, there were three little
pigs...";
2 $string2 = "Once upon a time, there were three bears...";
print "First string: $string1\n<br />";
print "Second string: $string2\n<br />";
3 $number=similar_text("$string1", "$string2", $percent);
print "There are $number of the same characters in the two
strings.\n";
4 echo "The strings are similar by " .
number_format($percent,
0). "%.<br />";
?>
</font>
</body>
</html>


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
!8%
5
":0%)'<'+.(%)*(',/)%.($%.))'/,$-%*0%1.('.2+$)4
P8%
Q
"#$%)'<'+.(e*$9*JK%&7,3*'0,%($*7(,)%*#$%,7<2$(%0&%3#.(.3*$()%*#.*%.($%*#$%).<$%.,-%.%
1.+7$%',-'3.*',/%*#$%6$(3$,*./$%0&%*#$%.+'A$,$))%0&%*#$%*:0%)*(',/)4%"#$=%.($%[Zf%
)'<'+.(4%B$$%C'/7($%D4!D4
%
Figure 6.16. The similar_text() function.

%
%

The levenshtein() function is used to find the Levenshtein
[2]
distance (also called the edit distance) between two
strings (strings cannot be longer than 255 characters). What’s that? Suppose you have two strings and you want to know
how you could edit one of the strings to make it just like the other string. (If you have ever used the UNIX diff
command, it will give you this kind of information.) The Levenshtein distance is defined as the fewest number of
insertions, substitutions, and deletions required to transform one string into another string. (The function is not case
sensitive.) The greater the Levenshtein distance, the more different the strings are. If the distance is 0, the strings are the
same. (For full discussion see Example 6.19 demonstrates how to use the
levenshtein() function.
[2]
Levenshtein distance is named after the Russian scientist Vladimir Levenshtein, who wrote the algorithm in 1965.
Format
int levenshtein ( string str1, string str2 [, int cost_ins [,
int cost_rep, int cost_del]] )
%
Example:
$diff = levenshtein($string1, $string2); $diff = levenshtein($string1, $string2,
100, 5, 1);

Example 6.19.
<html><head><title>Text that is Similar</title>
</head>
<body bgcolor="silver">
<font size="+1">
<?php
1 $string1 = "I attended a funeral.";

$string2 = "He attended a fun rally.";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
print "First string: $string1\n<br />";
print "Second string: $string2\n<br />";
2 $distance=levenshtein("$string1", "$string2");
print "It would take $distance changes to transform string1
into string2.<br />";
?>
</font>
</body>
</html>
Explanation
! ":0%)*(',/)%.($%.))'/,$-4%"#$=%#.1$%)0<$%3#.(.3*$()%',%30<<0,4%?#.*%:07+-%'*%*.A$%*0%
*(.,)&0(<%*#$%&'()*%)*(',/%',*0%*#$%)$30,-g
5 "#$%
levenshtein()
%&7,3*'0,%:'++%&'/7($%07*%*#$%<','<7<%,7<2$(%0&%',)$(*'0,)8%
-$+$*'0,)8%0(%)72)*'*7*'0,)%'*%:07+-%*.A$%*0%*(.,)&0(<%*#$%&'()*%)*(',/%',*0%*#$%)$30,-4%I,%
*#')%$9.<6+$8%*#$%&'()*%3#.,/$%:07+-%2$%
I
4%I*%:07+-%*.A$%*:0%)72)*'*7*'0,)%*0%3#.,/$%'*%*0%
He
4%"#$%,$9*%3#.,/$%:07+-%2$%*0%($6+.3$%*#$%
e
%',%&7,$(.+%:'*#%.%)6.3$%J*#($$%3#.,/$)%)0%
&.(K8%*#$,%*0%.--%*#$%
ly
%',%
rally
8%*:0%<0($%3#.,/$)8%<.A',/%.%*0*.+%0&%&'1$4%B$$%C'/7($%

D4!Z%&0(%07*67*4
%
Figure 6.17. The levenshtein() function.
%
%

The levenshtein() function includes the first two strings and three additional parameters that define the cost of
insert, substitute, and delete operations. This allows you to specify how you want scores weighted with numeric values.
Otherwise, all scores are given equal weight. The weight or cost indicates what steps should be taken to make the
strings similar; that is, should insertions or deletions be made to transform the string?
6.2.8. Splitting a String
PHP provides a number of functions to split strings. The split() and spliti() functions split up a string and
return an array. The explode() function splits up a string by a specified delimiter and returns an array. The
implode() function takes an array and joins the elements together to form a string. Because these functions require
that you understand PHP arrays and regular expressions, they are covered in Chapter 8, “Arrays,” and Chapter 12,
“Regular Expressions and Pattern Matching.” Table 6.9 provides the names of these functions, what they do, and where
to find a complete discussion and examples.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×