Dynadot Aftermarket: discover domain gems worth investing in. Visit our aftermarket.

Alternating string splits

Namecheap AuctionsNamecheap Auctions
Namecheap AuctionsNamecheap Auctions
SpaceshipSpaceship
Watch

Outer

Established Member
Impact
2
I need to know how to break a string up into alternating sizes.

for example, I need this string broken up: "hi, how are you, peace!"
so results are like this:
"hi"
", h"
"ow"
" ar"
" y"
"ou "
", p"
"eac"
"e!"

Note the spaces. Basically, I need a string to be cut up by a pattern of 2 characters, then 3 characters, then 2 characters, then three characters

How would I do that in PHP?

Thank You :)
 
0
Close
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
Try this (I think you forgot the 'e' in 'are' in your example =P)

PHP:
	$string = 'hi, how are you, peace!';

	function customSplitString($text) {
		$text_pieces = array();
		$offset = 0;
		$piece_length = 2;
		$str_length = strlen($text);
		
		for ($x=0; $offset < $str_length; $x++) {
			$piece_length = ($x % 2) ? 3 : 2;
			$text_pieces[] = substr($text, $offset, $piece_length);
			$offset += $piece_length;
		}
		return $text_pieces;
	}

	print_r(customSplitString($string));
 
0
Close
DomainEasy: white label portfolios are live. Enable yours.

We're social

Escrow.com
Spaceship
Domain Recover
CryptoExchange.com

NamePros updates

Switch between accounts
You can now stay logged in to more than one NamePros account in the same browser. Click your avatar, then "Accounts in this browser", to...
AIVikings
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back