Feeds:
Posts
Comments

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

Thanksgiving Turkey Brine

This year I decided to do something different with my turkey. Brining. This was something I had never heard of till this year and now that I know of it I will never cook another turkey any other way. So what I have decided to do is write up a little post describing the process I took. But before I get to that here is the basic recipe for a turkey brine. Now the items on this list can really be anything you want as long as the salt to liquid ratio is kept to 1 cup salt per 1 gallon of liquid. The amount of liquid will depend on the size of the turkey. You will want to have at least an inch of water above the turkey when you brine it. This is for an 18 pound turkey.

1 1/2 gallon water
3/4 gallon Pineapple juice
2 cups Kosher salt (very important! Cannot be iodized salt!)
2 cups sugar
Assortment of spices (I had 6 Bay Leaves, 2 tbl spoons of Cilantro, 5-6 pieces of Peppercorn, 2 tbl spoons of onion powder)

Now here is the process I took.

Two days before the big turkey day I prepared the brine. I put 1 gallon of water, 1 cup of salt, and 1 cup of sugar into a large pot. I then brought it to a boil so the salt and sugar would completely dissolve into the water. Once this was complete I added half the spices and mixed them together. I then moved the mixture into a large container to cool. I then repeated the process with the remaining ingredients. The following pictures are the results of the mixture.

I then put these into the fridge to get cold over night.

Now to brine a turkey you need to purchase a fresh turkey. It cannot be a frozen or kosher turkey. This is because with frozen or kosher turkeys they pre-inject it with a salt mixture to allow for the turkey to be moist when cooked. If you tried to brine a frozen turkey it would come out way to salty to eat. With this in mind I purchased an 18 pound fresh and all natural Butterball turkey. You can find these in the fresh meat department in your local grocery store. The one that I go to (Publix) puts them out no earlier then a week before thanksgiving. You will also want to brine the turkey for at least 12 hours. A good rule of thumb is 1 hour per pound but no more then 24 hours. I think 12 hours is plenty of time for the job to be done.

So the next night around 10pm I was ready to put the turkey in the brine mixture. They sell bags specific for brining but I had a hard time finding them. You can use XL Ziploc bags as well but yet again I could not find them. I did not have the time to order them online so I purchased 3 of the oven bake turkey sized bags. I also bought a large drink cooler to store it in overnight. You can use anything as long as it is plastic and clean. A bucket will work just as good.

I lined the cooler with the three bags and poured the now cold brining mixture into the bags. I then placed the turkey in with the large hole facing down. This was so I could make sure all parts of the turkey was being covered with the brine. You want to also make sure their are no air bubbles left. I then closed the top of the bags and placed a ziplock baggie full of ice on top to keep the turkey fully submerged and cold. Here are some picks of this part of the process.

I left the turkey in the brine mixture inside my fridge for the next 12 hours. The next day I took out the turkey, cleaned off all the brine mixture, and pat dry the turkey to remove any remaining salts. I then cooked the turkey as normal. Four hours later I had a nicely done turkey! The turkey came out fantastic! It was moist, had an excellent flavor to it and even looked good among the rest of the food. Here are some pictures of the turkey after it was cooked.

Well there it is :) My brining experience. I think the turkey came out better than ever and I am going to cook it this way from now on. I will be playing with the mixture of spices to get the perfect mix down! If you want to try this don’t hesitate! It is very simple and flexible. You can make any flavor you want.

Enjoy!
- Miah

Happy Thanksgiving

I hope everyone had a wonderful thanksgiving!

As this week has been hectic getting everything ready for the big turkey day I did not have time to prepare my weekly PHP Functions post. I will be back on schedule next week. I am going to instead prepare a post on brining a turkey. I had for the first time this year bought a fresh (non-frozen) turkey and took the challenge of brining the turkey before cooking it. It came out fantastic! I will have a post up describing the actual process I took tomorrow.

For now I will leave you with this!


function happyThanksgiving() {
    echo "Happy Thanksgiving!";
}

happyThanksgiving();

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

Tonight I’m going to put down something I learned just yesterday. How to easily migrate MySQL Databases across servers via the command line. Now I’m a beginner Linux Admin as my focus is on PHP Development but ever since I got myself a dedicated box at Rackspace I’ve had to learn a few tricks. Over the past month I have learned a host of them due to migrating from one Rackspace box to another. My biggest challenge was moving some of my MySQL Databases. A couple of them were quite large and PHPMyAdmin was just not up to the challenge. So after some searching and one phone call to the excellent Rackspace support team I had my solution and I am going to share this tidbit with you all.

The solution is something that any MySQL guru probably already knows but I think beginners and amateurs in command line techniques will benefit. It consist of three commands. They are as follows:

mysqldump --database --opt [DB NAME] > [DST FILE NAME].sql
scp [DST FILE NAME].sql [RMT BOX UN]@[RMT BOX IP]:[RMT BOX DST DIR]
mysql [DB NAME] < [TRANSFERRED FILE NAME].sql

The first and last commands are mysql commands and the middle one is a Linux command. What these three commands basically do when used in this sequence is:

  1. Dump a DB to a SQL file
  2. Transfer the created SQL file to another machine. (scp = Secure copy)
  3. Fill a DB with the contents of a SQL file.

When you run the scp command you will be prompted for the password associated with the username you are trying to connect with. Now scp only works on the same network but you can get around this by downloading the sql file via FTP and then uploading it to the destination machine.

You will also need to create the DB before running the last command.

Now this is pretty straight forward and easy to accomplish and now that I have this knowledge I am able to move databases in less then a minute! This made my last night of migrating painless. Also it will make things easy when I need to synce the servers DB’s with my own local machine for development or bug testing.

Here are links to the documentation for each command if you want to delve deeper into any of the available options.

mysqldump
scp
MySQL – The official website

All questions and comments are welcome!

Thanks,
- Miah

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 php.net 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'));
print_r($fruit);

// 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>";
    print_r($a);
    echo "</pre>";
}

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

// The output of this call is as follows:
Array
(
     [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.

Thanks,
- Miah

Fantasy Cartography

Well I’ve finally started to learn more then just the basics of Photoshop. I’ve for years have been able to scrap by with the bare minimum of knowledge with this vast program and to top it off my artistic skills are not the greatest when it comes to pen and paper.

With this in mind I am taking something I have always loved to do and using it to build up my skills. Making maps. I’ve always loved to sit down and draw out a world map, area map, or interior map for my fantasy/sci-fi RPG games. They were crude and done with graph paper mostly but they got the job done. Now however I am up for the challenge of making maps with a bit more flare and style.

I’m going through all the tips, tricks, and tutorials I can to help me along. One great site is the Cartographers Guild located at [link] They have a wealth of information to help map makers along. The vast amount of styles you can have for your maps can look overwhelming at first but once you get into actually making them the feeling passes quickly as you realize how many of the tricks can be used for the different styles of maps.

So here I am. Finally trying to improve my artistic skills. I’ll be using this to mark my progress and post all the maps I will be making!

Thanks for listening.

New years… Blarg!

So, here it is… September 19th and I haven’t kept up with any of my resolutions. Is this new? Nope. I think anyone can say that it is sometimes difficult to stick to your resolutions, especially when one of them concerns your weight. I Had such hopes for that one. I was doing very well while going to a personal trainer twice a week. I felt good, I was loosing weight and building some more muscle. Then something came along. I moved!

This is not a bad thing. I am very, very happy with my decision to move as I am now living in a house and not an apartment. But some things came with this that I wanted but kinda hindered the loosing weight a bit more than I wanted. I am now living in a house and working from home. I do not have a car or need one but with this comes the fact that I am always inside. I have also been more busy with work, also a good thing but with all of this combined it has killed my fitness routine. I had plans of walking every morning, using my Wii Fit, the tension cables my trainer gave me before I left and various other fitness activities to keep up with. So far I have done none of them. I am hoping to change that for the next couple months and redeem some of my lost steam before the end of the year.

I just launched a program for a client and the craziness that was that project should now be back to normal and back on some semblance of development cycles from here on out. This will let me manage my time better so I can hopefully squeeze in some walking and Wii Fit. I’ll also be able to manage my other clients better with this projects launch wrapped up.

My other goals I was not very good with either. Shaving everyday? Ha! That didn’t happen long :) Build miahandines.com? I haven’t even had a chance to start that site. To busy with paying clients to get any time to do the site. Web Games? Nothing their either. Same case as with miahandines.com. Wedding goal? The plans have changed once again their. We have decided again to pay off some of our debt before doing the wedding.

So I think the only thing I might be able to salvage is to lose some weight by the end of the year. It won’t be as much as I wanted but some is better than none.Well this wraps up my rant on my New Years resolutions. Till next time!

- Miah


We’re like super villains” — Jonathan, BTVS Season 6

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[gsv_i].selected) {
			value = selectList.options[gsv_i].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;
}

And now for the HTML:

<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

Week 1 Update

Well the first week is over. It is starting to be a slow start but I have good feelings that things will soon slide into place.

On the food front, it was rough. Wednesday my fiancée got sick and we stayed home. I worked from here but our schedule was thrown off so we didn’t quite eat as much or what we should have. The next few days did get better. Then today we slipped again. I stayed up late last night and woke up late which again threw off the schedule. Things will get back into place :)

Friday with the trainer was good. He had us focus on legs and biceps. Surprisingly I could walk this weekend! :) I attribute it to the protein shakes we are taking with the nutrition plan.

Well this is a short update. It’s late and I’ve been working all day and still have a few things to get done before I can call it a night.

- Miah

Older Posts »