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

Contact Us at blog.kerul.net

Powered by EMF HTML Contact Form

The Challenges of Handling Proverbs in Malay-English Machine Translation – a research paper

*This paper was presented in the 14th International Conference on Translation 2013 ( http://ppa14atf.usm.my/ ). 27 – 29 August 2013, Universiti Sains Malaysia, Penang. The PDF version is here: www.scribd.com/doc/163669571/Khirulnizam-The-Challenges-of-Automated-Detection-and-Translation-of-Malay-Proverb The test data is here: http://www.scribd.com/doc/163669588/Test-Data-for-the-Research-Paper-the-Challenges-of-Handling-Proverbs-in-Malay-English-Machine-Translation Khirulnizam Abd Rahman, Faculty of Information Science & Technology, KUIS Abstract: Proverb is a unique feature of Malay language in which a message or advice is not communicated indirectly through metaphoric phrases. However, the use of proverb will cause confusion or misinterpretation if one does not familiar with the phrases since they cannot be translated literally. This paper will discuss the process of automated filtering of Malay proverb in Malay text. The next process is translation. In machine translatio

WebDev

http://blog.kerul.net PHP DEVELOPMENT TOOLS Download the XAMPP latest version from www.apachefriends.org . This installation file contains the Apache web server, PHP 5 and 4 interpreter, and the MySQL 5 Community edition. - download latest version MozillaFireFox (OpenSource web browser firefox) – download latest version Google Chrome – fastest web browser on earcth – fast download chrome here TEACHING PLAN Download the teaching plan here for Web/Internet Programming ( download ) NOTES HTML references HTML Editor -  http://www.sublimetext.com/ Lab 1: HTML Basics -  http://www.w3schools.com/html/ Lab 2: Responsive Design:  http://www.w3schools.com/html/html_responsive.asp Lab 3: HTML Forms  http://www.w3schools.com/html/html_forms.asp Lab 4: HTML 5  http://www.w3schools.com/html/html5_intro.asp Lab 5: Bootstrap for responsive Web -  http://www.w3schools.com/bootstra

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)