Fri, 17 May 2024


Str_Split PHP Function

By: Peter, NetArt Media
Wed, 1 August 2018
Str_Split PHP Function

Splitting a string up according to how we would like isn't too, too difficult to do with PHP. When you know the parameters that can be used and how to go about using them you can come up with some interesting results. I will cover a few basic examples in this article, hopefully providing some ideas if you plan on ever using this particular function.


Here is a string of 5 words, each written into the definition according to how I planned on splitting them up. By using a character length of 5 and knowing I want to break each word up according to 5 spaces, I left 2 blank spaces after the word 'Are'. Str_split recognizes white space as part of the resulting length, so keep that in mind.

The result of this str_split code block is...

These | Are | Split | Words

You are probably taking notice of the offsets I used for displaying each piece of the string. We use those in arrays, thus by using str_split we are in fact turning our string into an array before manipulating it. If we were to var_dump the results instead of using offsets, this would be our result.

array (size=4)
0 => string 'These' (length=5)
1 => string 'Are ' (length=5)
2 => string 'Split' (length=5)
3 => string 'Words' (length=5)


Now let's do some mathematics using the PHP str_split function.


I changed the amount of character space to 1, from 5, and created a string of numbers in an even increment from 2 to 8. By simply placing '*' between each offset chunk of the string we create a mathematical equation that gives us the sum of the string of numbers.

2+4+6+8 = 20


Now I will split up two sentences in a string according to their character lengths. I set the length at 90 and as long as the character count is equal to or under that amount we can split the two sentences accordingly.


The result would be...

This is a paragraph about something or other that I would like to split onto two lines.

This is the second line that I would like to put under it using str_split.

This would be a rather crude way of going about breaking up strings of text, but in a pinch it might be what the PHP doctor called for. These are just examples to show you the interesting things that str_split and it's similar PHP functions can do. And I will certainly be covered most of them here at PHP-Scripting in the future.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox