Page 1 of 1

Splitting a string into blocks

Posted: Tue Oct 26, 2004 9:13 am
by mjseaden
Hi

Is there any PHP string function I can use to split a string into blocks of 20 characters? Say for instance I had ********************####################(((((((((((((((;;;;;;;;;;;;;;;;;;;;

This would split the string into blocks of 20 characters and return each in an array?

Many thanks

Mark

Posted: Tue Oct 26, 2004 9:50 am
by mjseaden
OKay - I think chunk_strings does this - however I can't find a function similar to Visual Basic's left() or right() functions, which take X number of characters off the beginning or end of a string. Is there any PHP equivlent (ltrim and rtrim are not the same as these functions)?

Posted: Tue Oct 26, 2004 10:15 am
by hokiecsgrad
There's no function that I know of that will do what you want, but one shouldn't be too hard to write:

Code: Select all

<?php

function splitString( $str, $numChars ) {

  $strArray = array();
  while ( strlen( $str ) > 0 ) {
    array_push( $strArray, substr( $str, 0, $numChars ) );
    $str = substr( $str, $numChars );
  }

  return $strArray;

}

$myArray = array();
$myString = "********************####################(((((((((((((((;;;;;;;;;;;;;;;;;;;; ";
$myArray = splitString( $myString, 20 );

echo "<pre>"; print_r( $myArray ); echo "</pre>";

?>

Posted: Tue Oct 26, 2004 10:16 am
by mjseaden
Thanks very much!

Posted: Tue Oct 26, 2004 10:27 am
by mjseaden
Hi - I can't seem to find them. Where's the PHP equivalent of left() and right() functions to strip X characters from the left or right end of a string?

Many thanks

Mark

Posted: Tue Oct 26, 2004 10:35 am
by timvw
[php_man]substr[/php_man]

would go like

Code: Select all

function splitter($sentence, $length)
{
  $parts = array();
  while (strlen($sentence) > $length)
  {
    $parts[] = substr($sentence, 0, $length);
    $sentence = substr($sentence, $length);
  }
  $parts[] = $sentence;
  return $parts;
}

Posted: Tue Oct 26, 2004 10:51 am
by mjseaden
timvw,

Could you use this as a left/right end of a string trimming function? This seems like a fairly basic thing to do but I can't seem to find the right function or combination of functions.

Many thanks

Mark

Posted: Tue Oct 26, 2004 10:56 am
by timvw
if i understand well, that is exactly what [php_man]substr[/php_man] does

string substr ( string string, int start [, int length])

substr() returns the portion of string specified by the start and length parameters.