Skip to main content

Most used STRING functions in my PHP coding

PHP String functions

These are my favourite string manipulation functions in my daily coding life. Dedicated especially to Web Programming students. Read them and have fun. Expect a happiness after a storm , and you’ll find your “inner peace”…

This post is still in draft. I’ll update and refine with more examples that I’ve personally develop. More after the break…

For more info head straight to the official tutorial.

  1. String functions.
  2. Multibytes String functions (Unicode).

 

EXAMPLE 1

addslashes — Quote string with slashes

in the example, the addslashes function prevents the SQL string from being misinterpreted by the single quote in the middle of the search criteria.

<html>
<head><title>Test addslashes() function</title></head>
<body>
<h3>Test form </h3><br>
<form name="formtest" method= "GET" action="">
INPUT
<input name="txtinput" type="text" size="30"><br>
<input name="btnSubmit" type="submit" value="addslashes">
<input name="btnReset" type="reset" value="Reset">
</form>
<hr>
<?php
$in=$_GET["txtinput"];
if ($in==NULL){
echo "Pls enter a string with quote";
}
else{
$sql="SELECT * FROM employee WHERE firstname = '".addslashes($in)."'";
echo $sql;
}
?>

</body>
</html>


image


stripslashes– this is the inverse of addslashes where you remove backslashes from a string.


 


EXAMPLE 2


strlen — Get string length


substr — Return part of a string


In the example, I’m trying to extract birthdate information from a Malaysian IC numbers.


<html>
<head><title>Test substr() function</title></head>
<body>
<h3>Date of birth extracted from Malaysian IC numbers </h3>
Malaysian Identification Card has 12 digits.
The first 6 digits are actually birthdate of the holder
in the format of yymmdd.
<br>
<form name="formtest" method= "GET" action="">
Enter your IC
<input name="txtic" type="text" size="12" maxlength="12"><br>
<input name="btnSubmit" type="submit" value="extract birthdate">
<input name="btnReset" type="reset" value="Reset">
</form>
<hr>
<?php
$ic=$_GET["txtic"];
if ($ic!=NULL && ctype_digit($ic) && strlen($ic)==12){
// $ic!=NULL - to check there's actually input in the textbox
// ctype_digit($ic) - all characters are number
// strlen($ic)==12 - to check there are 12 digits
$year=substr($ic,0,2);//extract digit 1 and 2
$month=substr($ic,2,2);//extract digit 3 and 4
$day=substr($ic,4,2);//extract digit 5 and 6

echo "The IC holder birthdate is: ";
echo "$day/$month/$year (dd/mm/yy)";// date format dd/mm/yy
}
else{
echo "Enter an IC number (must be in 12 digits format)";
}
?>

</body>
</html>


Extract birthdate from Malaysian IC number


 


EXAMPLE 3


htmlentities — Convert all applicable characters to HTML entities


in the example, I’m trying to print a HTML tag into the HTML page.


<html>
<head>
<title>Test htmlentities</title>
</head>

<body>
<form name="formtest" method= "GET" action="">
Write the HTML tage to create a hyperlink to connect to http://kerul.net<br>
<textarea name="txtcode"></textarea>
<br>
<input name="btnSubmit" type="submit" value="convert to htmlentities">
</form>
<hr>
<?php
$code=$_GET["txtcode"];
//echo " $ic <br>";
if ($code!=NULL ){

echo "Your answer (this is without htmlentities)";
echo $code;
echo "<br>\n";
echo "Your answer (this is after htmlentities)";
echo htmlentities($code);
echo "<br>\n";


}else{
echo "Please provide the code";
}
?>
</body>
</html>

The output;

image


See the HTML tag for the page,


image


html_entity_decode — Convert all HTML entities to their applicable characters


 


EXAMPLE 4 – String to number (big integer)


FYI, the maximum range for an integer value in PHP variable is 2147483647. I got this from the code;


<?php
echo PHP_INT_MAX; //to get the maximum integer value PHP variable can hold
?>


Guest what happen if I run this code to check Malaysian IC number whether it’s ODD or EVEN (input comes from a textbox – means it in STRING). Malaysian IC number consists of 12 digits number.


<form name="formtest"  method= "GET"  action="">
Enter your IC
<input name="txtic" type="text"maxlength="12"><br>
<input name="btnSubmit" type="submit" value="test IC">
</form>
<hr>
<?php
$ic=$_GET["txtic"];
echo " $ic <br>";
if ($ic!=NULL && ctype_digit($ic) && strlen($ic)==12){
if ($ic%2==0){//IC is even
echo "IC number is EVEN";
}
else{
echo "IC number is ODD";
}
}else{
echo "IT IS NOT A VALID IC NUMBER";
}
?>

image

It will always tell you the number is ODD…

 

Why? Not quite sure why. Yet the solution is simple. Add 0 to the $ic as in the following code, and problem solved. They said it something to do with changing the integer variable into unsigned…

<form name="formtest"  method= "GET"  action="">
Enter your IC
<input name="txtic" type="text"maxlength="12"><br>
<input name="btnSubmit" type="submit" value="test IC">
</form>
<hr>
<?php
$ic=$_GET["txtic"];
$ic=$ic+0;
echo " $ic <br>";
if ($ic!=NULL && ctype_digit($ic) && strlen($ic)==12){
if ($ic%2==0){//IC is even
echo "IC number is EVEN";
}
else{
echo "IC number is ODD";
}
}else{
echo "IT IS NOT A VALID IC NUMBER";
}
?>


 

 

 

similar_text — Calculate the similarity between two strings


 


md5 — Calculate the md5 hash of a string


money_format — Formats a number as a currency string


echo — Output one or more strings


printf — Output a formatted string


str_word_count — Return information about words used in a string


strtok — Tokenize string


trim — Strip *whitespaces (or other characters) from the beginning and end of a string


ucwords — Uppercase the first character of each word in a string


*Whitespaces are hidden characters such as space, tab and newline.


 


EXERCISE – String Functions


Exercise 1: Accept a date in dd/mm/yyyy format and convert into ISO date (yyyy-mm-dd). Make sure the input format is correct before converting to another format.


Answer:



<form method="get" action="">
Date <input type="text" name="txtdate">
format (dd/mm/yyyy)<br>
<input type="submit">
</form>
<?php
$date=$_GET['txtdate'];
if (strlen($date)==10){

$day=substr($date, 0, 2);
$month=substr($date, 3, 2);
$year=substr($date, 6, 4);

if(ctype_digit($day)&&ctype_digit($month)&&ctype_digit($year)){
//display
echo "Input date: $date<br>";
echo "ISO date: $year-$month-$day";
}
else{
echo "Date format not valid <br>";
}
}
else{
echo "Date format not valid <br>";
}
?>

Exercise 2: Accept a date in ISO format (yyyy-mm-dd) and convert to dd MONTH yyyy. Make sure the input format is correct before converting to another format.

Eg: Accept 2011-07-14 as the input, and output 14 JULY 2011


Answer:


<form method="GET" action="">
Task: Convert ISO date (yyyy-mm-dd) into dd NAME_OF_MONTH yyyy <br>
Input ISO date<input type="text" maxlength=10 name="txtisodate">
(format: yyyy-mm-dd)<br>
<input type="submit" value="Convert">

</form>
<hr>
Output
<br>

<?php
$date=$_GET['txtisodate'];
if (strlen($date)==10){

$year=substr($date, 0, 4);
$month=substr($date, 5, 2);
$day=substr($date, 8, 2);

if(ctype_digit($day)&&ctype_digit($month)&&ctype_digit($year)){
//display
echo "Input ISO date: $date<br>";
if($month=="01")
$monthname="January";
else if ($month=="01")
$monthname="February";
else if ($month=="02")
$monthname="February";
else if ($month=="03")
$monthname="March";
else if ($month=="04")
$monthname="April";
else if ($month=="05")
$monthname="May";
else if ($month=="06")
$monthname="June";
else if ($month=="07")
$monthname="July";
else if ($month=="08")
$monthname="August";
else if ($month=="09")
$monthname="September";
else if ($month=="10")
$monthname="October";
else if ($month=="11")
$monthname="November";
else if ($month=="12")
$monthname="December";
else
$month="NOT_VALID_VALUE";
echo "After conversion: $day $monthname $year";

}
else{
echo "Date format not valid <br>";
}
}
else{
echo "Date format not valid <br>";
}
?>

Comments

Popular posts from this blog

Several English proverbs and the Malay pair

Or you could download here for the Malay proverbs app – https://play.google.com/store/apps/details?id=net.kerul.peribahasa English proverbs and the Malay pair Corpus Reference: Amir Muslim, 2009. Peribahasa dan ungkapan Inggeris-Melayu. DBP, Kuala Lumpur http://books.google.com.my/books/about/Peribahasa_dan_ungkapan_Inggeris_Melayu.html?id=bgwwQwAACAAJ CTRL+F to search Proverbs in English Definition in English Similar Malay Proverbs Definition in Malay 1 Where there is a country, there are people. A country must have people. Ada air adalah ikan. Ada negeri adalah rakyatnya. 2 Dry bread at home is better than roast meat home's the best hujan emas di negeri orang,hujan batu di negeri sendiri Betapa baik pun tempat orang, baik lagi tempat sendiri. 3 There's no accounting for tastes We can't assume that every people have a same feel Kepala sama hitam hati lain-lain. Dalam kehidupan ini, setiap insan berbeza cara, kesukaan, perangai, tabia...

Pemasangan Joomla! 1.7 pada pelayan web komputer anda

Latihan ini akan memasang sistem pengurusan kandungan laman web ke dalam pelayan web yang anda telah pasang sebelum ini . LANGKAH 1: Aktifkan Pelayan Web dan Pangkalan Data Aktifkan XAMPP Control Panel, melalui “ Start->All Programs->ApacheFriends->XAMPP Control Panel ”. Rajah 2.1 Pastikan pelayan web Apache dan pelayan pangkalan data MySQL diaktifkan dengan klik butang START. -> Rajah 2.2

Installing Google AdMob into Android Apps

Previously I wrote on why ads are needed to help maintaining an app. Read the article here http://blog.kerul.net/2011/05/generating-revenue-from-free-mobile.html . ---This is quite an old article. You may find the latest supporting AdMob 6.x in here http://blog.kerul.net/2012/08/example-how-to-install-google-admob-6x.html --- This is quite a long tutorial, there are 3 major steps involved. The experiment is done using Windows 7, Eclipse Helios and AdMob SDK 4.1.0 (which currently is the latest-during time of writing). STEP 1: Get the ads from AdMob.com To display the AdMob ads in your Android mobile apps, you need to register first at the admob.com . After completing the registration, login and Add Site/App. Refer to Figure 1. Figure 1 Choose the desired platform and fill in the details (as in Figure 2). Just put http:// in the Android Package URL if your app is not published in the market yet. And click Continue. Figure 2 Download the AdMob Android SDK, and save the zip fil...

ViewFlipper Example–a simple FlashCard

UPDATE: Improved with Fling gesture (Sept 2012) UPDATE: ViewFlipper with Flip-In and Flip-Out Animation (August 2012) This tutorial is to demonstrate the ViewFlipper layout that is almost similar to CardLayout (in Java). The app will produce a simple Flash card that provide several screens with different picture for each card. Flip-in and Flip-out animation provided. Added in Sept 2012 – an improvement to support Fling gesture – enjoy… The amendment is only on the coding part. Some how the layout design (main.xml) is quite long. Later I’ll produce separated screen by including several XML layout from outside files. Screenshots;

Submit your blog address here

Create your own blog and send the address by submitting the comment of this article. Make sure to provide your full name, matrix and URL address of your blog. Refer to the picture below. Manual on developing a blog using blogger.com and AdSense, download here … Download Windows Live Writer (a superb offline blog post editor)