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

Bootstrap Template for PHP database system - MyCompanyHR

HTML without framework is dull. Doing hard-coded CSS and JS are quite difficult with no promising result on cross platform compatibility. So I decided to explore BootStrap as they said it is the most popular web framework. What is BootStrap? - Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. (  http://www.w3schools.com/bootstrap/   ) Available here -  http://getbootstrap.com/ Why you need Flat-UI? Seems like a beautiful theme to make my site look professional. Anyway you could get variety of BootStrap theme out there, feel free to select here  http://bootstraphero.com/the-big-badass-list-of-twitter-bootstrap-resources/ Flat-UI is from DesignModo -   http://designmodo.com/flat/ Web Programming MyCompanyHR – PHP & MySQL mini project (with Boostrap HTML framework) Template 1: Template for the Lab Exercise. This is a project sample of a staff record management system. It has the PHP structured co

Keperluan untuk pemasangan Joomla! 1.7 pada komputer anda

Eksperimen ini akan memasang perisian keperluan sebelum anda memasang Joomla!. Perisian yang diperlukan ialah XAMPP1.7.4 (versi Windows)*. Projek ini dilakukan pada Windows 7. LANGKAH 1: Muat turun XAMPP Memandangkan XAMPP telah membuat kompilasi semua keperluan di atas (pelayan web Apache, penterjemah PHP dan pelayan pangkalan data MySQL), jadi anda cuma perlu muat turun XAMPP dari laman web berikut; http://www.apachefriends.org/en/xampp-windows.html

Contact Us at blog.kerul.net

Powered by EMF HTML Contact Form

Simple Calculator with Spinner – Android Code

This code is a simple code for Android application. It has two textboxes to receive two numbers (decimal), list of mathematical operations with +, –, * and /. Choose the operation, and hit the “Display result” button. You will see the answer to the at the bottom of the button. Have fun with Android.   The Manifest file <? xml version="1.0" encoding="utf-8" ?> < LinearLayout xmlns : android = "http://schemas.android.com/apk/res/android" android : orientation = "vertical" android : layout_width = "fill_parent" android : layout_height = "fill_parent" > < EditText android : text = "@+id/EditText01" android : id = "@+id/EditText01" android : layout_width = "fill_parent" android : layout_height = "wrap_content" > </ EditText > < EditText android : text = "@+id/EditText02" android : id = "@+id/EditText02"