Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
String Functions
empty()
strlen()
strrev()
str_repeat()
substr()
strcmp()
str_word_count()
str_replace()
trim()
strtolower()
strtoupper()
ucfirst()
ucwords()
addslashes()
stripslashes()
htmlentities()
htmlspecialchars()
nl2br()
html_entity_decode()
htmlspecialchars_decode()
strip_tags()
Sample
The strlen() function returns the number of characters in a string.
<?php
$str='WelcometoPHP';
echostrlen($str);
?>
Reverse a string
<?php
$str=Comtech';
echostrrev($str);
?>
In case you need to repeat a string, PHP offers the str_repeat() function, which
accepts two argumentsthe string to be repeated, and the number of times to
repeat it.
<?php
$str='PHP';
echostr_repeat($str,3);
?>
PHP also allows you to slice a string into smaller parts with the substr() function,
which accepts three arguments: the original string, the position (offset) at which
to startslicing, and the number of characters to return from the starting position.
1 PHP Made Easy from Comtech Authors
<?php
$str='Welcometonowhere';
echosubstr($str,3,4);
?>
If you need to perform substitution within a string, PHP also has the str_replace()
function, designed specifically to perform find-and-replace operations. This
functionaccepts three arguments: the search term, the replacement term, and
the string in which toperform the replacement.
<?php
// replace '@' with 'at'
$str = 'comtech@manaparai.in';
echo str_replace('@', ' at ', $str);
?>
Formatting Strings
PHPs trim() function can be used to remove leading or trailing whitespace from a
string;this is quite useful when processing data entered into a Web form.
<?php
//removeleadingandtrailingwhitespace
//output'abc'
$str='abc';
echotrim($str);
?>
$str='ComtechWelcomesyoutoPHP';
echostrtolower($str);
echostrtoupper($str);
?>
You can also uppercase the first character of a string with the ucfirst()function, or
format a string in word case with the ucwords()function.
<?php
$str='comtechwelcomeyou';
echoucwords($str);
echoucfirst($str);
?>
//output:'ComtechWelcomeYou'
//output:'Comtechwelcomeyou'
You can reverse the work done by addslashes()with the aptly named
stripslashes()function, which removes all the backslashes from a string.
<?php
//removeslashes
$str="JohnD\'Souzasays\"Catchyoulater\".";
echostripslashes($str);
//output:'JohnD'Souzasays"Catchyoulater".'
?>
Month (string)
Month (string)
Month (numeric)
Year
AM or PM
Minute
Second
strtotime() -
gmdate()
You can also do this for month names, by using the date() functions 'F'
parameter:
<?php
//displaylistofmonthnames
//output:'January,February,...December'
foreach(range(1,12)as$m){
$months[]=date('F',mktime(0,0,0,$m,1,0));
}
echoimplode($months,',');
?>
<?php
//returnsGMTtimerelativeto'now'
echogmdate('H:i:sdMY',mktime());
//returnsGMTtimerelativeto'00:011Dec2007'output:'18:31:0030Nov2007'
echogmdate('H:i:sdMY',mktime(0,1,0,12,1,2007));
?>
ceil()
Rounds a number up
floor()
abs()
pow()
log()
exp()
rand()
bindec()
decbin()
decoct()
dechex()
hexdec()
octdec()
number_format()
printf()
Theres also the abs() function, which returns the absolute value of a number.
<?php
//returnabsolutevalueofnumber
//output:19.7
$num=19.7;
echoabs($num);
?>
The pow() function returns the value of a number raised to the power of another:
<?php
//calculate4^3
//output:64
echopow(4,3);
?>
The log() function calculates the natural or base-10 logarithm of a number, while
theexp() function calculates the exponent of a number.
<?php
//calculatenaturallogof100
//output:2.30258509299
echolog(10);
//calculatelogof100,base10
//output:2
echolog(100,10);
//calculateexponentof2.30258509299
//output:9.99999999996
echoexp(2.30258509299);
?>
Generating random numbers with PHP is pretty simple too: the languages builtinrand() function automatically generates a random integer greater than 0. You
canconstrain it to a specific number range by providing optional limits as
arguments.
<?php
//generatearandomnumber
echorand();
//generatearandomnumberbetween10and99
echorand(10,99);
?>
Formatting Numbers
When it comes to formatting numbers, PHP offers the number_format() function,
which accepts four arguments: the number to be formatted, the number of
decimal places todisplay, the character to use instead of a decimal point, and the
character to use to separategrouped thousands (usually a comma).
<?php
//formatnumber(withdefaults)
//output:1,106,483
$num=1106482.5843;
echonumber_format($num);
//formatnumber(withcustomseparators)
//output:1?106?482*584
echonumber_format($num,3,'*','?');
?>
For more control over number formatting, PHP offers the printf() and sprintf()
functions. These functions, though very useful, can be intimidating to new users,
andso the best way to understand them is with an example.
<?php
//formatasdecimalnumber
//output:00065
printf("%05d",65);
//formatasfloatingpointnumber
//output:00239.000
printf("%09.3f",239);
//formatasoctalnumber
//output:10
printf("%4o",8);
//formatnumber
//incorporateintostring
//output:'Isee8applesand26.00oranges'
printf("Isee%4dapplesand%4.2foranges",8,26);
?>
Both functions accept two arguments, a series of format specifiers and the raw
string ornumber to be formatted. The input is then formatted according to the
format specifiers and the output either displayed with printf() or assigned to a
variable with sprintf().
Some common format specifiers are listed in Table.
%s
String
%d
Decimal number
%x
Hexadecimal number
%o
Octal number
%f
Floating-point number
You can also combine these format specifiers with a precision specifier, which
indicates the number of digits to display for floating-point valuesfor example,
%1.2f implies that the number should be formatted as a floating-point value with
two digits displayed after the decimal point. For smaller numbers, its also
possible to add a padding specifier, which tells the function to pad the numbers
to a specified length using a custom character. You can see both these types of
specifiers in action in the preceding listing.