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 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


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

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
} 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 */
            $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 */

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

PHP Functions 101 – print_r()

Hello all, this will be the first in a weekly tradition I am starting today. Every Thursday night I plan on publishing an article on one PHP function. I will start with the ones I use most frequently then move onto the more obscure ones so I can digest and learn all I can while passing that knowledge to others.

So to start of this week I’ll go with a function I use quit often while I am building a website; print_r(). Here is the official description taken straight form the manual on what this function does:

Prints human-readable information about a variable

Now what does this mean exactly? It is really quit simple. The function takes a variable, it doesn’t matter the type. It could be an Object, Array, or a simple integer and it spits it out onto the screen so you can see exactly what it is. It is pretty useful when building and debugging a script.

One word of caution when using it though. Since it can and will most likely be displaying sesitive information about your application you want to use it in a secure environment if at all possible. If not then at least in a development environment (which should be secured anyways). If this is not possible I will use it on a refresh then quickly comment it out so it will hopefully not be seen by regular users. I hate doing this so in these cases I also add in an IF statement to only show the output to my IP address. The morale of this long rant. Be cautious, as you don’t want to allow any kind of security leak.

Now that my security rant is over lets move on. The print_r() function takes one required parameter and one optional parameter. They are as follows:

mixed $expression
bool  $return = false [optional]

The first parameter is the actual variable you are examining.

The second parameter is optional and defaults to false. All this does is tell the function to either display the results to the screen or return the results as a variable for later use. I have never yet had a reason to set this optional parameter to true. Now onto some examples.

We have just used the print_r() function to print to the screen an array of fruit names for an application we are working on. Here is the code:

$fruit = array('Apple','Mango','Banana', array('Strawberry','Blueberry','Cranberry'));

// The output of this call is as follows:
Array ( [0] => Apple [1] => Mango [2] => Banana [3] => Array ( [0] => Strawberry [1] => Blueberry [2] => Cranberry ) )

This is pretty useful if you have a complicated script and need to see what is inside an array or object that is set in another file or are the results of a DB query. The only problem I find with this is the output. With the example above it isn’t too bad but if you have a large array or object you are examining it can get very messy  and confusing to look at. What I have done to overcome this shortfall to the function is create my own modification of it. The function is rather quite simple. I have seen people do this trick but since I like to write as little code as possible whenever I can and to reuse my code I created a function to accomplish it. My solution to the output problem is this:

function print_a($a) {
    echo "<pre>";
    echo "</pre>";

$fruit = array('Apple','Mango','Banana', array('Strawberry','Blueberry','Cranberry'));

// The output of this call is as follows:
     [0] => Apple
     [1] => Mango
     [2] => Banana
     [3] => Array
         [0] => Strawberry
         [1] => Blueberry
         [2] => Cranberry

Now we have a much more readable output and can understand the structure of the array much easier.What makes this possible is by echoing out the HTML <PRE> tabs. What these tags do is allow for text to display correctly within the browser as it is written. It keeps all it’s formatting and white space  which is normally stripped out by the browser. With the function I created to accomplish this I can call print_a() in replace of print_r() any where in my code to have nicely formatted output with out any extra code.

For a wrap up. The print_r() function is a very useful function when building an application or debugging one. It allows you to examine any variable or expression to get a better understanding of it’s structure and what it contains. It is most useful when examining arrays and objects. You also have to be mindful of where you use it as you don’t want to expose sensitive data to the world. The function also prints the results, although readable, in an ugly format when not surrounded by the HTML <PRE> tags. Using a costume function like mine above you can get nicely formatted output without having to surround each call or print_r() with the <pre> tag.

I hope this has been helpful and any and all comments are welcome. If you know any more information you think should be added to this let me know and I’ll be glad to add it and give credit to the addition. Next week I’ll discuss another function from the PHP library that I use often, array_push(). If you would like me to discuss a certain topic please let me know.

– Miah