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:
[code lang=”php”]
$TextString = "some text to split")
$Columns = SplitIntoColumns ($TextString, 2, "<h1>");
echo ($Columns[0]);
echo ($Columns[1]);
[/code]

Function
[code lang=”php”]
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;

}
[/code]

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

4 comments

  1. hi
    I have us the same problem but I want to change the code so it is like this now

    $Pos .= strpos($InputString, $SplitString);
    if ($Pos === false) {
    $Pos = strlen($InputString);
    }

  2. Hi,When you download the file, do you see two shetes Instructions sheet and Data sheet?When i download the file, i see the macro when i press Alt+F8.Pasting the code here will cause more problems because straight quotes will be replaced by smart quotes.

Leave a Reply to :c Cancel reply

Your email address will not be published. Required fields are marked *