String Replace

Now we arrive in the string replace tutorial of PHP.Like I said earlier, we won’t be covering all of the string functions, mainly because this is more of an introductory tutorial rather than an advanced reference guide. However, if you can understand these few functions, it should be easy for you to manipulate strings using the other functions. The string replace function is extremely useful in managing strings. Let’s fight our way through an example.
Example
$myString = "The meerkat clan was victorious.";
echo str_replace("meerkat","squirrel",$myString);
ResultThe squirrel clan was victorious.
Wow! We just changed the result of the war with a simple PHP string function.We tell PHP to look for all occurrences of “meerkat” and replace it with “squirrel” in our string variable $myString.PHP runs through and does exact matches for each and every instance, which means if we had the word “meerkat” in that string a million times, PHP would replace it with the word “squirrel” a million times. Of course, you can also use string replace as a way to delete characters or words from a string by making the second parameter “”. PHP would go through and replace the word with an empty string.Another useful note here is that you can use the string replace function with arrays to save you time and effort of having to learn more functions. The string replace function is cases sensitive, so if you were to search for “MEERKAT”, you wouldn’t have changed anything. Also, there is actually a forth parameters, which you can put a number in to tell PHP the number of characters or words you want to replace.If you want to dig deeper, you should look into the preg_replace function that using regular expressions to perform the matches, but I tried to keep string replacement simple for you. That is it, you are now a master of PHP’s string replace function.

String Position

Now, we dive into the world of strings and all of the crazy functions. Well, not exactly, but we will actually dive into a few of the really major string functions so that you have an understanding of how to work with strings in PHP. You might notice that PHP has a lot of functions and not methods, which means you can’t call something like string.method for these functions. First, we will start off with using the string position function in PHP. Example, please!

Example
$myString = "The meerkat clan was victorious.";
echo strpos($myString, "meerkat",0);
Result 4

The result you get should be 4, unless I failed you. Upon an examination of this code, we see that we have a string variable that has the contents “The meerkat clan was victorious.” We then echo the result of our strpos function. Our strpos function takes $myString and searches for our next parameter, “meerkat”, beginning from our starting index of 0. If we count out the string, T is 0, h is 1, e is 2, the space is 3, and we have the word meerkat that starts at a position of 4. String position can be used this way, but it is often used with some other function like when you watch to get a part of a string when using the substr function.

Sometimes, you might use strpos to have an easy way to check if something is in a string. While not the most ideal function to use, it does the trick. We know the strpos function returns the index of the match, but what happens when it doesn’t find a match? In that case, it returns -1, so we can create an if statement that has a conditional checking if the strpos function returns something greater than -1.

I should mention a few things before we close this tutorial. The strpos function is case-sensitive, which means if I would have searched for “MEERKAT”, it have returned a negative one, which means it didn’t find a match. Also, the 0 we have is an optional parameterthat tells our search were to begin in the string. So, if we would have had 10 instead of 0, we wouldn’t have returned anything either. This is because “meerkat” begins on the index of 4. You can use this argument to get sub strings between certain words. Enough with PHP’s string position. Bring on the next string function!

strpos vs strrpos

Often, we assume that strpos and strrpos are the same. Well, the do the same function, but they approach it two different ways. strpos finds the first occurrence of the matching item in the string and returns its position in the string. strrpos starts from the end and returns the position of the last occurrence in the string.

Comments

We arrive at the cornerstone of all languages, including PHP, comments. I cannot stress the importance of commenting your code. As a webmaster, I create all kinds of web applications, but more importantly, I maintain the code previously crafted before I arrived. So many times, I have wondered “what the heck were they doing here?”…And after about 10-20 minutes of digesting their code, do I truly understand what they were trying to accomplish. Please comment. Please. With that being said, try to not over comment either. It is fine to do it on every few lines starting out as a beginner. However, when you get more advanced, try to comment large sections (each function and at least every 30 lines) and explain what you are doing in the following code.

Enough of the lecturing, how do I actually comment? Commenting is super easy just like in other languages. In PHP, you can make comments in two ways.

Comment Out One Line

Example <html>
<body>
<?php
//echo “I am awesome!”;
#echo “I am awesome!”;
echo “I am really awesome!”;
?>
</body>
</html>
Result I am really awesome!

Obviously, the // only comments until semicolon or until the end of the line. It does not require a closing partner. The # works exactly the same way as the previous comment. The other type of comment, is a block comment, which allows you to comment out more than one stupid line. It lets you comment out however much you want.

The Multiline Comment

Example <html>
<body>
<?php
/*echo “I am awesome!”;
echo “I am really awesome!”;
*/
echo “I am super awesome!”;
?>
</body>
</html>
Result I am super awesome!

The /* requires the closing tag of */. Everything in between these tags is completely ignored as PHP code. This comment is perfect for testing your code, blocking out code that is not needed right now, and writing a paragraph on what your following code is supposed to do.

String Explode and Implode

Onto my two favorite string functions in PHP, explode and implode.

PHP Explode

The explode function is awesome because it breaks a string into manageable parts, like words. You can easily create a PHP program using explode and other PHP functions to create a program that performs a word count. I crafted a program like this in college because I have a terrible tendency to use the same words, and apparently professors think that means you have a limited mind. I showed them. Enough bragging, more coding.

Example
$myString = "I am a long and redundant sentence that serves no purpose except to be an example.";
print_r(explode(" ",$myString));
Result Array ( [0] => I [1] => am [2] => a [3] => long [4] => and [5] => redundant [6] => sentence [7] => that [8] => serves [9] => no [10] => purpose [11] => except [12] => to [13] => be [14] => an [15] => example. )

We employ our print_r class to print out our array in a way that is readable. Inside that function, we have our explode function. First, we say that we want to separate everything by spaces, ” “, and we want to break up $myString. We could pass anything we want into the first parameter, and PHP will find any matches and explode the parts around it into an array. However, when you match something using explode, it does not include the matched string. In our example, we matched spaces, but in our array the spaces are completely eliminated. There is a third optional parameter to limit the number of words you want to break up, which you can add on the end. PHP Explode is finished. Let’s be more constructive in the next section.

PHP Implode

Enough of blowing things apart. Let’s start putting them back together with the PHP implode function. The implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array. Ok, we’re sorry. We’ll put it back together.

Example
$myString = "I am a long and redundant sentence that serves no purpose except to be an example.";
$newArray = explode(" ",$myString);
echo implode(" ",$newArray);
Result I am a long and redundant sentence that serves no purpose except to be an example.

Our code is almost identical to the example above, but we are not printing it out until we use our next function implode. In our implode function, we simply say we want to join all of the items in our array $newArray together, but please separate them with a space, ” “. Boom! We blew a string into pieces, and then put it again together like a boss.

For Loop

PHP for loops are a complicated concept. It is a combination of a statement, a condition, and another statement. Basically, a loop is a repeating if statement. Let’s just go ahead and jump into an example.

Example for($i = 0; $i < 5; $i++) //statement 1 var $i = 0; condition $i<5; statement2 $i++;
{
echo $i; //write current value of variable $i
echo ‘<br/>’;
}
echo ” End of for loop “;
Result 0
1
2
3
4
End of for loop

The for loop is somewhat like a modified if statement that restarts itself until the condition is satisfied. Inside of the for loop, we have the statement $i = 0; that declares a variable $i and sets it equal to 0. Next, we have the conditional $i < 5 that is the if part of the statement. We know that the conditional says if $i < 5, then run the statements in the { }. Finally, we have an increment operator statement, $i++, which is the most commonly used way to advance a for loop. Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we echo $i for the first time it is 0 rather than 1. So, we run through the statements in the { } and we get the results 0,1,2,3,4. Right after the final execution of statements, $i is incremented to 5, which was then compared against the conditional $i < 5. It is obviously false at this stage; therefore, we move outside of the for loop and we execute the next line of code that happens to be our echo ” End of for loop “; statement.

PHP For Loop iteration

In the image above, we can see how PHP runs through a for loop. Every time all of the code has been executed in the parentheses, PHP goes back up and checks the condition in the for loop. If the condition is still true, PHP executes the code in the parentheses again until the condition is no longer true.