Part of string -> Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Korken
Forum Newbie
Posts: 10
Joined: Thu Jul 02, 2009 8:07 am
Location: Luleå, Sweden

Part of string -> Array

Post by Korken »

Hello!

I've got a little problem with string -> array.
I have a string and I want that some parts of it becomes an array, in the string there are keywords it should react to.
Example:

Code: Select all

String: weeee<tis>Into array 1</tis>someandomtext<tis>Into array 2</tis>morerandomtext<tis>Into array 3</tis>andsomemore
Output array:
Array
{
    [0] => "Into array 1"
    [1] => "Into array 2"
    [2] => "Into array 3"
}
I've got no idea on how to do this so abit of a push in the right direction would be great!

Thanks!

//Emil
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Part of string -> Array

Post by pickle »

I'm not sure if there's some magical combination of built-in functions to do this. My first solution would be to search the string for <tis>, and remove everything up to and including the tag. Then, search the remainder for </tis>. Put everything in the newly cropped string up to the beginning of the </tis> tag into the array, remove the </tis> tag, then continue.

Pseudo code

Code: Select all

$string = weeee<tis>Into array 1</tis>someandomtext<tis>Into array 2</tis>morerandomtext<tis>Into array 3</tis>andsomemore
while(<tis> is found in $string)
{
  $position = position of <tis> in $string;
  $string = everything after $position + 5
  if(</tis> is found in string)
  {
    $position = position of </tis> string;
    $array[] = everything from beginning of $string to $position
    $string = everything after $position + 6
  }
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
mickeyf
Forum Newbie
Posts: 3
Joined: Mon Jul 27, 2009 5:18 pm

Re: Part of string -> Array

Post by mickeyf »

If I'm understanding what you want correctly, this sounds like very nearly a job for the 'explode' function, except that you have two distinct delimiters <tis> and </tis>. It might even work to replace </tis> with <tis> then use explode...plus a little coding allowance for overhangs...
User avatar
Korken
Forum Newbie
Posts: 10
Joined: Thu Jul 02, 2009 8:07 am
Location: Luleå, Sweden

Re: Part of string -> Array

Post by Korken »

Thanks!

I've got a general idea of how to do it now. :)

//Emil
Post Reply