Monday, 21 March 2011

How to Use PHP Substr

As you get more involved in using PHP, you will no doubt need to modify PHP strings at some point. While this should be easy, the instructions on the PHP website are not that clear. In this article, I will provide you with some examples and how to go about learning to manipulate PHP strings using substr.

For many of you reading this article, I probably know just how you feel about modifying PHP strings and variables. It should be easy but it is simply hard to find an exact example of what you want to do. As you go to the PHP website, there are many hard core techie explanations but no simply clear explanation that says exactly what to do.

The best way to go about understanding PHP strings is to get a test page setup. To do this, you will need a website and the ability to copy files there. After trying many webhosts, I use HostGator because their uptime and reliability have been great.

Once you have the ability to test your files on the Internet, you can try many permutations of manipulating strings in PHP.

I will give you two examples and then you will be off and running.

First, let's use Notepad or your favorite text editor (mine is UltraEdit) to create a text file which we will name stringexample.php. In this file, let's add the following five lines:



When you upload this file to your website and then access it on your website, you can see that the result is "love this article directory". What did we do? We removed the first two characters of the PHP string using the PHP substr command. What is important to note here is that the PHP string character numbering begins at 0. So, we simply used substr and said "show me this whole variable starting at the third character.

Now, what if want to simply remove the word directory plus the space in front of it but include the rest of the variable.

Well, in that case, we would change the line substr line to the following:

$thename = substr($thename,0,-10);

This tells the PHP substr command to start at the first character of the variable and remove 10 characters at the end.

In summary, PHP substr is not complex. You can achieve a lot with just a few simple command. However, finding the exact command is difficult. I hope that this article helped you with how to use PHP substr and setup your environment so that you can do a lot of quick testing.

No comments:

Post a Comment

Computers and Technology..Share Computers, Technology Basic Windows, Linux And Game