Quantcast
Viewing latest article 3
Browse Latest Browse All 4

Split text into multiple columns in PHP

I made a Swedish shopping directory using affiliate links for a site and wanted to split it into two columns.

I wrote the following php function that can be used to split a string in two or more pieces. One parameter is at what character or string you want to split. For example if you want to split at a space to not break up words, or split at a period to not split up sentences, at certain html tags such as <h1> to keep headlines and text in same column etc.

The function returns a string array with columns.

Example how to use:

	$TextString = "some text to split")
	$Columns = SplitIntoColumns ($TextString, 2, "<h1>");
	echo ($Columns[0]);
	echo ($Columns[1]);

Function

function SplitIntoColumns ($InputString, $Columns, $SplitString) {

	// Source: http://blog.tjitjing.com
	// 
	// Splits a string into x number of columns and returns result as an array of columns
	//
	// Parameters:
	// $InputString	String to be split into columns
	// $Columns		Number of columns
	// $SplitString	String to look for to not split midtext etc
	//
	// Change history:
	// 2011-01-25/Max	Version 1
	//

	// Find middle of text
	$ColLength = strlen($InputString)/$Columns;

	// Split into columns
	for($ColCount = 1; $ColCount <= $Columns; $ColCount++) {

		// Find $SplitString, position to cut
		$Pos = strpos($InputString , $SplitString , $LastPos + $ColLength);
		if ($Pos === false) {
			$Pos = strlen($InputString);
		}

		// Cut out column
		$Output[$ColCount - 1] = substr($InputString, $LastPos, $Pos - $LastPos);

		$LastPos = $Pos;
	
	}

	return $Output;

 }

[Edit: VB.NET version: Split text in two columns in VB.NET]


Viewing latest article 3
Browse Latest Browse All 4

Trending Articles