PHP Functions 101 – str_replace()

Welcome back. We’re in the midst of the holidays and I hope ever one is having a good time. I know It has been eventful so far for me. Anywho, this week I’ll do a quick overview of the str_replace() function. This is another function I use often in my projects. It is useful when you need to quickly replace parts of a string. It doesn’t take regular expressions so if you don’t need them then this is the function for you as it is quicker and less processor intensive. Please note however that it is case-sensitive. If you need to replace with case-insensitive strings use str_ireplace(). This function acts identical to str_replace except that it is case-insensitive.

Moving forward. Here is the official description taken from php.net for the str_replace() function:

Replace all occurrences of the search string with the replacement string

The function takes three required parameters and a fourth optional parameter. They are as follows:

mixed $search
mixed $replace
mixed $subject
int $count [optional]

The first parameter, $search, is the values you want to replace. This can be a single string or an array of multiple strings.

We next have $replace. This is the values you want to replace the $search values with. If $search is an array and $replace is a string then it will replace all occurrences in $search with the same value. If $replace is an array with a smaller size then $search then all remaining $search terms will be replaced with an empty string.

Lastly is $subject. This is the string or array that will be searched through. If it is an array each element will have the search and replace action performed. str_replace() will also return an array if the $subject is an array.

$count is the only optional variable. If a variable is passed it will be filled with the number of matches and replacements that have occurred.

Now that we have defined the function and gone over the parameters here are some examples:


// replace some values in a simple string
$string = "The house on the left is made up of wooden boards";

$modified = str_replace("left","right",$string);
echo $modified; // Outputs: The house on the right is made up of wooden boards

$modified = str_replace(array("left","wooden"),"green",$string);
echo $modified; // Outputs: The house on the green is made up of green boards

$modified = str_replace(array("left","wooden","boards"),array("green","stone"),$string);
echo $modified; // Outputs: The house on the green is made up of stone

$modified = str_replace(array("left","wooden boards"),array("right","brick"),$string);
echo $modified; // Outputs: The house on the right is made up of brick

The above examples are pretty simple but I think they show the basic use of the str_replace() function. Now there are a couple things to watch out for when using this function. You need to take care with the order you are replacing items with. The function will replace all items in the first index of the $search array, then continue to the next index and so on and so forth. This may give unexpected results. Here is an examples of this.


$string = "a simple apple tree";

$modified = str_replace(array("a","e"),$array("e","X"),$string);
echo $modified; // Outputs: X simplX XpplX trXX

In this example it replaces all occurrences of “a” with “e“. It then replaces all occurrences of “e” (including the ones that were placed when “a” was replaced) with “X“. I don’t run into this that often but it is something you will want to keep in mind.

Well this is it for this week. I hope as always that is was helpful to someone out there 🙂 Next week I’ll deal with strstr(). As always, thanks for reading.

– Miah

Advertisements

PHP Functions 101 – array_push()

Hello and welcome back for my next installment of PHP Functions 101. This week I’ll be discussing the array_push() function. This is another simple function that I use often when dealing with arrays. Here is the definition from php.net:

Push one or more elements onto the end of array

This is a simple function. As the definition states above it simply pushes an element onto an existing array. You can push any kind of element; an object, simple variables, even other arrays. The function takes at least two parameters. The first being the array we are adding (pushing) the elements onto and the remaining variables are the elements to be added (pushed) onto the array. You can push as many elements on as you want.

Here are a couple examples. I’ll do a simple one then a more complex example.


// The big 'ol array that stores everything
$bigOlArray = array();

// Simple variables
$someString = "This is a simple string";
$someInteger = 42;
$configurationArray = array(
    "id" => "x302",
    "power" => "Asgard",
    "weapons" => true,
    "shields" => true,
    "shieldLevels" => 100
    );
$strikeFirst = false;

// Push them all into the same array
array_push($bigOlArray, $someString, $someInteger, $configurationArray, $strikeFirst);

With this example we simple made the main array, $bigOlArray, and then created a bunch of different variables then pushed them all onto the one array. This next example will hopefully be a more practical use of the funciton. I will use it to read in a file and take all the configuration info from the file and combine it into an array using the array_push() function.


/* Open the file we want to read in */
$fh = fopen("/path/to/file/the_file",'r');

if (!$fh) {
    // Put error checking code here
    exit();
} else {
    $elementData = array();
    $temp = array();
    $newField = false;
    $value = "";

    // Loop through the file
    while (!feof($fh) {
        $line = fgets($fh);
        if (strstr($line,'[END FIELD]')) {
            if ($newField) {
                /* Put the temp config array into the element array */
                array_push($elementData,$temp);
            }
            $newField = false;
            $temp = array();
        } else  if (strstr($line,'[FIELD]')) {
            $newField = true;
        }

        if ($newField) {
            /* Add the configuration line to the temp array */
            $ft = explode(" = ",$line);
            if (isset($ft[1])) {
                if (trim($ft[1]) == "true") {
                    $value = true;
                } else if (trim($ft[1]) == 'false') {
                    $value = false;
                } else {
                    $value = trim($ft[1]);
                }
                $temp[$ft[0]] = $value;
            }
        }
    }
}

/* Close the file */
fclose($fh);

What this script does is read in a file, then it searches for field definitions. Once it finds one it reads each line of the field definition into a temp array. Once it reaches the end it pushes the entire array onto the end of the main elements array. The script keeps this up till it reaches the end of the file where it then closes the connection to the file. PHP does have a function called parse_ini_file() which will do basically the same thing. It reads a configuration file and returns it as an associative array. I’m hoping though that the example above gave some insight in how you can use the function and the power it can have.

Well I hope this has brought something to a few readers out their. I haven’t decided yet what I will do for next week. Maybe It’ll probrably be one of the various string funcitons like strstr() or str_replace() or something similar. As always if you have any requests let me know 🙂

Thanks for reading!
– Miah

Getting Form Values with Javascript

I am building a CRM/Scripting System/Scheduler for a client and I needed an easy wrapper function to quickly grab the value of a form input with javascript. I use alot of AJAX and was noticing that I was repeating the same set of code over and over and over and over…. You get the jist 🙂 In programming this is a bad idea. You want to strive for reusable code. Now the code I was writting over again is pretty simple but I still wanted to save myself some typing, another thing you strive for as a programmer, so I came up with a couple simple wrapper functions that will get me the value of a form input with a single function call.

Without further ado:

/**
 * Returns the value of a select box. It will 
 * work for both a multiselect box and a normal
 * select box.
 *
 * The function returns an string of the selected
 * values separated by a ','.
 */
function getSelectValue(selID) {

	var selectList = document.getElementById(selID);
	var optionsLength = selectList.options.length;
	
	var results = "";
	
	for (gsv_i = 0; gsv_i < optionsLength; gsv_i++) {
		if (selectList.options&#91;gsv_i&#93;.selected) {
			value = selectList.options&#91;gsv_i&#93;.value
			if (results == "") {
				results = results + value;
			} else {
				results = results + "," + value;
			} 
		}
	}

	return results;
}

/**
 * Returns the value of a form input.
 */
function getInputValue(id) {

	if (document.getElementById(id).type.indexOf('select') != -1) {
		// We have a select element. Lets call the function for selects.
		return getSelectValue(id);
	} else {
		// Else we will just return the value of the element
		return document.getElementById(id).value;
	}
	
}

/**
  * USAGE 
  */

function getTestValues() {
	var inputValue = getInputValue('textInput');
	var selectValue = getInputValue('selectInput');

	alert(inputValue);
	alert(selectValue);

	return false;
}

&#91;/sourcecode&#93;

And now for the HTML:

&#91;sourcecode language='html'&#93;
<input type="text" name="textInput" id="textInput" value="Some Value" />
<select name="selectInput" id="selectInput">
	<option value="option 1">Option 1</option>
	<option value="option 2">Option 2</option>
	<option value="option 3">Option 3</option>
</select>

<script type="text/javascript">
	getTestValues();
</script>

Since I’m not a Javascript guru I am not guaranteeing this is the best way to do this. It is just what I found most convenient for me and I believe will be convenient for others 🙂

I hope you enjoy and if you have questions feel free to ask 🙂

Later!
– Miah


I believe that’s the dance of a brave little toaster.” – Xander, Something Blue