Fri, 17 May 2024
NetArt Media     Pay 2, Get 3!    


Substr PHP Function

By: Nathalie, NetArt Media
Wed, 1 August 2018
Substr PHP Function

In a nutshell, the substr PHP function is used to pull out certain pieces of a string and return them according to how it's starting and ending parameters are set. While a fairly limited function, in conjunction with other functions it can be quite useful within a script.

Here is a basic substr example which returns the first 7 characters of a string of 9 numbers, all separated with a space in order to display them in a readable manner. White spaces are counted as a character when using substr, so keep that in mind.


This would be the result of the above substr code.

1 2 3 4

We can also use negative parameters with substr.


'-1' tells the substr function to go to the end of the string. '1' tells it to return the last character of the string in conjunction with the negative starting point.

The result of the above substr script would be..

9

Here's another example where I bring the numbers 5 and 6 close together and tell substr to return 3 characters after the first 7 characters, starting from the beginning of the string.


The result of this particular example will be '56'. Without the quotes. ;-)

Now I will take a different approach to using the substr PHP function. I will simplify the script by eliminating the parameters, but will use square brackets within the echo code to pick out particular numbers from the string and multiply them. Notice that I brought the numbers close together in the string definition for this example.


Viewed in a browser, the result of this example is...

4 x 9 = 36

So there we have some examples of how the PHP substr function can work. It's the kind of function you can play around with and come up with all kinds of different results. Again, by itself it will not make for a full script. However, together with several different PHP functions it can be quite handy to have in your tool box.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox