Sie sind auf Seite 1von 10

PHP Library Functions

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

Tests if a string is empty


Calculates the number of characters in a string
Reverses a string
Repeats a string
Retrieves a section of a string
Compares two strings
Calculates the number of words in a string
Replaces parts of a string
Removes leading and trailing whitespace from a string
Lowercases a string
Uppercases a string
Uppercases the first character of a string
Uppercases the first character of every word of a string
Escapes special characters in a string with backslashes
Removes backslashes from a string
Encodes HTML within a string
Encodes special HTML characters within a string
Replaces line breaks in a string with <br/>elements
Decodes HTML entities within a string
Decodes special HTML characters within a string
Removes PHP and HTML code from a string

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

Comparing, Counting, and Replacing Strings


If you need to compare two strings, the strcmp() function performs a casesensitivecomparison of two strings, returning a negative value if the first is less
than the second,a positive value if its the other way around, and zero if both
strings are equal.
<?php
$a="hello";
$b="hello";
$c="hEllo";
echostrcmp($a,$b);
echostrcmp($a,$c);
?>

PHPs str_word_count() function provides an easy way to count the number


ofwords in a string.
<?php
$str="Thename'sBond,JamesBond";
echostr_word_count($str);
?>

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

Changing the case of a string is as simple as calling the strtolower()or


strtoupper()function
<?php

2 PHP Made Easy from Comtech Authors

$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'

Working with HTML Strings


PHP also has some functions exclusively for working with HTML strings. First up, the
addslashes()function, which automatically escapes special characters in a string
withbackslashes. Heres an example:
<?php
//escapespecialcharacters
//output:'You\'reawake,aren\'tyou?'
$str="You'reawake,aren'tyou?";
echoaddslashes($str);
?>

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".'
?>

The htmlentities()and htmlspecialchars()functions automatically


convertspecial HTML symbols (like <and >) into their corresponding HTML
representations (&lt;and &<hairline#>gt;). Similarly, the nl2br()function
automatically replaces newlinecharacters in a string with the corresponding HTML
line break tag <br/>.
<?php
//replacewithHTMLentities
//output:'&lt;divwidth=&quot;200&quot;&gt;
//Thisisadiv&lt;/div&gt;'
$html='<divwidth="200">Thisisadiv</div>';
echohtmlentities($html);
//replacelinebreakswith<br/>s
//output:'Thisisabro<br/>
//kenline'
$lines='Thisisabro
kenline';
echonl2br($lines);
?>

3 PHP Made Easy from Comtech Authors

You can reverse the effect of the htmlentities()and


htmlspecialchars()functions with the html_entity_decode()and
htmlspecialchars_decode()functions. Finally, the strip_tags()function searches
for all HTML and PHP code within astring and removes it to generate a clean string.
Heres an example:
<?php
//stripHTMLtagsfromstring
//output:'Pleaseloginagain'
$html='<divwidth="200">Please<strong>loginagain</strong></div>';
echostrip_tags($html);
?>

Dates and Times


Generating Dates and Times
To get the current date and time is with PHPs getdate()function, which returns an
associative array containing information about the current date and time.Heres an
example of what this array looks like:
Array
(
[seconds]=>33
[minutes]=>27
[hours]=>19
[mday]=>12
[wday]=>1
[mon]=>11
[year]=>2007
[yday]=>315
[weekday]=>Monday
[month]=>November
[0]=>1194875853
)

And heres an example of this function in action:


<?php
//getcurrentdateandtimeasarray
$now=getdate();
//output:'Itisnow19:26:23on12112007'
echo'Itisnow'.$now['hours'].':'.$now['minutes'].':'
.$now['seconds'].'on'.$now['mday'].''.$now['mon'].''
.$now['year'];
?>

Formatting Dates and Times


In most cases, generating a timestamp is only half the battle: you also
need to find away to display it in human-readable form. Thats where
PHPs date() function comesin: it allows you to massage that long, ugly
timestamp into something thats much moreinformative. This function
accepts two arguments: a formatting string and a timestamp.The
4 PHP Made Easy from Comtech Authors

formatting string is a sequence of characters, each of which has a special


meaning;Table has a list of the most commonly used ones.
<?php
//output:"Itisnow12:28pm20Mar2008"
echo'Itisnow'.date("h:iadMY",mktime(12,28,13,3,20,2008));
//output:"Itisnow8:1514Feb2008"
echo'Itisnow'.date("H:idFY",mktime(8,15,0,2,14,2008));
//output:"Today'sdateisOct052007"
echo'Today\'sdateis'.date("MdY",mktime(0,0,0,10,5,2007));
?>

Day of the month (numeric)

Day of the week (string)

Day of the week (string)

Month (string)

Month (string)

Month (numeric)

Year

Hour (in 12-hour format)

Hour (in 24-hour format)

AM or PM

Minute

Second

Useful Date and Time Functions


PHP also supports many other date/time manipulation functions, which
allow you to checkif a date is valid or convert between time zones. Table
4-3 lists some of these functions.
checkdate()

strtotime() -

Creates timestamps from English-language descriptions

gmdate()

Expresses a timestamp in GMT

Checks a date for validity

Checking Date Validity


A useful built-in function is the checkdate()function, which accepts a month,
day,and year combination and returns a true/false value indicating whether the

5 PHP Made Easy from Comtech Authors

correspondingdate is valid. Consider the following example, which illustrates it by


testing the date30 February 2008:
<?php
//output:'Dateisinvalid'
if(checkdate(2,30,2008)){
echo'Dateisvalid';
}else{
echo'Dateisinvalid';
}
?>

Converting Strings to Timestamps


Another very useful function is PHPs strtotime()function, which accepts a
stringvalue containing an embedded date or time and converts this into a UNIX
timestamp.Heres an example:
<?php
//definestringcontainingdatevalue
//convertittoUNIXtimestamp
//reformatitusingdate()
//output:'07Jul08'
$str='July72008';
echodate('dMy',strtotime($str));
?>

Interestingly, strtotime()also recognizes common time descriptions such as"now",


"3hoursago", "tomorrow", or "nextFriday". The following listingillustrates this
very useful feature:
<?php
//output:'12Nov07'
echodate('dMy',strtotime('now'));
//output:'13Nov07'
echodate('dMy',strtotime('tomorrow'));
//output:'16Nov07'
echodate('dMy',strtotime('nextFriday'));
//output:'10Nov07'
echodate('dMy',strtotime('48hoursago'));
?>

Mapping Day and Month Numbers to Names


The date() function discussed in the preceding section isnt useful only for
formattingtimestamps into readable date strings; it can also be used to
find the weekday namecorresponding to a particular date. To do this,
simply use the 'D' format character withyour timestamp . . . as in the
following example, which displays the day that Oct 5 2008falls on:
<?php
//output:'Sun'
echodate('D',mktime(0,0,0,10,5,2008));
?>

You can also do this for month names, by using the date() functions 'F'
parameter:

6 PHP Made Easy from Comtech Authors

<?php
//displaylistofmonthnames
//output:'January,February,...December'
foreach(range(1,12)as$m){
$months[]=date('F',mktime(0,0,0,$m,1,0));
}
echoimplode($months,',');
?>

Calculating GMT Time


PHPs gmdate() function works exactly like its date() function, except that
it returnsGMT representations of formatted date strings, instead of local
time representations. Tosee this in action, consider the following
examples, which return GMT equivalents for twolocal times:

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

Using Numeric Functions


PHP language has over 50 built-infunctions for working with numbers, ranging
from simple formatting functions tofunctions for arithmetic, logarithmic, and
trigonometric manipulations.
Doing Calculus
A common task when working with numbers involves rounding them up and
down. PHP offersthe ceil() and floor() functions for this task
<?php
//roundnumberup
//output:19
$num=19.7;
echofloor($num);
//roundnumberdown
//output:20
echoceil($num);
%>

ceil()

Rounds a number up

floor()

Rounds a number down

abs()

Finds the absolute value of a number

pow()

Raises one number to the power of another

log()

Finds the logarithm of a number


7 PHP Made Easy from Comtech Authors

exp()

Finds the exponent of a number

rand()

Generates a random number

bindec()

Converts a number from binary to decimal

decbin()

Converts a number from decimal to binary

decoct()

Converts a number from decimal to octal

dechex()

Converts a number from decimal to hexadecimal

hexdec()

Converts a number from hexadecimal to decimal

octdec()

Converts a number from octal to decimal

number_format()

Formats a number with grouped thousands and decimals

printf()

Formats a number using a custom specification

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

8 PHP Made Easy from Comtech Authors

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

Converting Between Number Bases


PHP comes with built-in functions for converting between binary, decimal, octal,
andhexadecimal bases. Heres an example which demonstrates the bindec(),
decbin(), decoct(), dechex(), hexdec(), and octdec() functions in action:
<?php
//converttobinary
//output:1000
echodecbin(8);
//converttohexadecimal
//output:8
echodechex(8);
//converttooctal
//output:10
echodecoct(8);
//convertfromoctal
//output:8
echoctdec(10);
//convertfromhexadecimal
//output:101
echohexdec(65);
//convertfrombinary
//output:8
echobindec(1000);
?>

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,'*','?');

9 PHP Made Easy from Comtech Authors

?>

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.

10 PHP Made Easy from Comtech Authors

Das könnte Ihnen auch gefallen