PHP: String Functions Web App

Chapter four, Strings, in “PHP The Good Parts” (MacIntyre, Peter B. PHP: The Good Parts. USA: O’Reilly, 2010) contained a great list of useful PHP string functions. I thought what better way to get to understand how these work than to build a PHP web app demonstrating them:

String Functions Web App

Screen capture of PHP string functions web app

Along the way, I used a PHP form referencing the $_POST array from chapter two and added in jQuery to handle some data storage and display and on-the-fly form modifications.

Let’s take a look at the code behind this web app.

There are five files involved in this app:

php_strings_web_app.php – starting PHP page
php_strings_web_app2.php – PHP page called from the form
php_strings_web_app.js – jQuery code for the PHP page
php_strings_web_app.css – CSS for the PHP page
jquery-1.6.4.min.js – jQuery library file

php_strings_web_app.php

We start off with some standard HTML5 code to set up our page, include our CSS and JS files and provide some introductory information.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP: String Functions Web App</title>
    <script type="text/javascript" src="jquery-1.6.4.min.js"></script>
	<script type="text/javascript" src="php_strings_web_app.js"></script>	
    <link href="php_strings_web_app.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<h2>PHP: String Functions Web App</h2>	
	<em>This web app demonstrates various PHP string functions. It is written in PHP with HTML5 and uses jQuery for storing and displaying additional data and modifying the form on the fly.</em>
	<br><br>

Next we set up our form and close off the HTML5 code. This form will use the POST method on the server to submit the form and call a second PHP file, php_strings_web_app2.php, where we will use the PHP $_POST array to retrieve the form data.

There are four main elements in this form:

  • text input tag myStringVar where the user types a string
  • drop-down list tag lstStringFunc where the user selects a string function to be called on myStringVar
  • span tag stringFuncDetails where additional form elements will be added as needed by jQuery
  • submit input tag to submit the form
<form method="post" action="php_strings_web_app2.php">       
    $myStringVar = <input type="text" name="myStringVar" value="Type a string!" />
	<br><br>	
	<select id="lstStringFunc" name="lstStringFunc">
		<option value="ltrim">ltrim</option>		
		<option value="rtrim">rtrim</option>
		<option value="trim">trim</option>
		<option value="strtoupper">strtoupper</option>
		<option value="strtolower">strtolower</option>
		<option value="ucwords">ucwords</option>		
		<option value="ucfirst">ucfirst</option>
		<option value="lcfirst">lcfirst</option>
		<option value="str_word_count">str_word_count</option>
		<option value="strlen">strlen</option>
		<option value="strstr">strstr</option>
		<option value="stristr">stristr</option>
		<option value="strpos">strpos</option>
		<option value="str_replace">str_replace</option>
		<option value="substr">substr</option>
		<option value="strip_tags">strip_tags</option>
		<option value="addslashes">addslashes</option>
		<option value="stripslashes">stripslashes</option>
		<option value="htmlentities">htmlentities</option>
		<option value="html_entity_decode">html_entity_decode</option>
		<option value="str_shuffle">str_shuffle</option>
		<option value="md5">md5</option>
	</select>
	<span id="stringFuncDetails">($myStringVar)</span>
    <input type="submit" value="Update" />	
</form>
</body>
</html>

php_strings_web_app2.php

This called file is very similar to our starting PHP file. The only differences are that there is a block of PHP occurring in at the start of our form which will call our string function and display the results, and there is a new div where we will display information on the PHP string function that was just called.

Important points on this code:

  • $_POST array is used to access the value of our lstStringFunc drop-down list in the form and our text fields
  • depending on the string function to be called, we process it accordingly, by including other text field values (more on that in a bit!) in the proper order
  • echo is used to display output to the user on what string function was called with what parameters and the result
  • there is a div called moreInfo where we will be adding information on the PHP string function called using jQuery
<form method="post" action="php_strings_web_app2.php">       
	$myStringVar = <input type="text" name="myStringVar" value="Type a string!" />
	<br><br>	
	<?php
		$stringFuncToRun = $_POST['lstStringFunc'];
		$stringFuncOutput = "";
		if (($stringFuncToRun == "strstr") || ($stringFuncToRun == "stristr") || ($stringFuncToRun == "strpos")) {
			$myNewStringVar = $stringFuncToRun($_POST['myStringVar'], $_POST['myStringVar2']);
			$stringFuncOutput = "\"" . $_POST['myStringVar'] . "\", \"" . $_POST['myStringVar2'] . "\"";
		}
		else if ($stringFuncToRun == "str_replace") {
			$myNewStringVar = $stringFuncToRun($_POST['myStringVar2'], $_POST['myStringVar3'], $_POST['myStringVar']);
			$stringFuncOutput = "\"" . $_POST['myStringVar2'] . "\", \"" . $_POST['myStringVar3'] . "\", \"" . $_POST['myStringVar'] . "\"";
		}
		else if ($stringFuncToRun == "substr") {
			$myNewStringVar = $stringFuncToRun($_POST['myStringVar'], $_POST['myStringVar2'], $_POST['myStringVar3']);
			$stringFuncOutput = "\"" . $_POST['myStringVar'] . "\", " . $_POST['myStringVar2'] . ", " . $_POST['myStringVar3'];
		}
		else if ($stringFuncToRun == "strip_tags") {
			$myNewStringVar = $stringFuncToRun($_POST['myStringVar'], $_POST['myStringVar2']);
			$stringFuncOutput = "\"" . $_POST['myStringVar'] . "\", \"" . $_POST['myStringVar2'] . "\"";
		}
		else {		
			$myNewStringVar = $stringFuncToRun($_POST['myStringVar']);
			$stringFuncOutput = "\"" . $_POST['myStringVar'] . "\"";
		}		
		echo "<span class=\"stringFunc\">" . $_POST['lstStringFunc'] . "</span>(" . $stringFuncOutput . ") = \"" . $myNewStringVar . "\"";
	?>
	<br><br><br>
	<div id="moreInfo">loading...</div>
	<br><br>
	<select id="lstStringFunc" name="lstStringFunc">
		<option value="ltrim">ltrim</option>	

php_strings_web_app.js

In our jQuery file, we first of all include some standard jQuery code that indicates we will run this code as soon as the document is ready, followed by an associative array to define the information on each string function by the string function keys that match those used in the lstStringFunc drop-down list back in our PHP files.

$(function() {
	var stringFuncDesc = new Array();
	stringFuncDesc["ltrim"] = " removes leading whitespace from a string.";
	stringFuncDesc["rtrim"] = " removes trailing whitespace from a string.";
	stringFuncDesc["trim"] = " removes whitespace from both ends of a string.";
	stringFuncDesc["strtoupper"] = " changes all characters in the string to uppercase.";
	stringFuncDesc["strtolower"] = " changes all characters in the string to lowercase.";	
	stringFuncDesc["ucwords"] = " changes the first character of each word in the string to uppercase.";	
	stringFuncDesc["ucfirst"] = " changes the first character in the string to uppercase.";	
	stringFuncDesc["lcfirst"] = " changes the first character in the string to lowercase (first available in PHP 5.3).";

Next we define some additional actions to take place based on the activity in our PHP form.

The first section will modify the HTML of the moreInfo div back on the PHP page to contain the name of the string function called and it’s description from the jQuery associative array. This will occur on “show” of the moreInfo tag, so whenever our second PHP page loads.

The second section will add or remove additional text fields required in the form based on the string function to be called. This will occur on “change” of our lstStringFunc drop-down list, so whenever we select a new item in the drop-down list.

At the bottom of the jQuery file, we ensure to finish our jQuery code with });.

$("#moreInfo").show(function() {
		$("#moreInfo").html("<strong>" + $(".stringFunc").html() + "</strong> " + stringFuncDesc[$(".stringFunc").html()]);
	});
$("#lstStringFunc").change(function() {
		if (($("#lstStringFunc").val() == "strstr") || ($("#lstStringFunc").val() == "stristr") || ($("#lstStringFunc").val() == "strpos")) {
			$("#stringFuncDetails").html("(\$myStringVar, <input type=\"text\" name=\"myStringVar2\" value=\"Type a substring!\" />)");		
		}
		else if ($("#lstStringFunc").val() == "str_replace") {
			$("#stringFuncDetails").html("(<input type=\"text\" name=\"myStringVar2\" value=\"Type a substring!\" />, <input type=\"text\" name=\"myStringVar3\" value=\"Type a replacement!\" />, \$myStringVar)");
		}

php_strings_web_app2.css

Some simple CSS rounds out our web app by providing some body style and a style for our string function details.

body 
{
    background-color: #ffffff;
    font-family: Verdana, Arial, Sans-Serif;
    font-size: 11px;
}
#moreInfo
{
	padding: 5px;
	border: 1px solid #000000;
	background-color: #ffff99;
	max-width:400px;	
}

Some thoughts on this solution:

  • The use of two very similar PHP files could probably be improved upon. Essentially the second file is always used after the first submission of the form, so further improvement could be to find a way to use just the second file but ensure that there are no errors thrown in the PHP code for the first time the file is launched, or perhaps use AJAX to update the form while still on the page.
  • The use of jQuery may not have been completely necessary, there are probably PHP methods to complete the same tasks, but since I am working through PHP bit by bit, and had jQuery familiarity, this seemed to be a good compromise to still show the heart of the solution while adding a little additional functionality easily. It also showed how I could combine PHP and jQuery.
  • The app could populate the text field with the last string result, to save the learner from re-typing/pasting it in to try additional string functions on the most recent result. The drop-down list could also remember the last item chosen. How to accomplish these easily should become apparent while working through more on PHP.
  • Further down the line as well, the string function descriptions could be stored alternatively, like a JSON file or a database, depending on what would provide more benefit.

Enjoy!