Jump to content

[SOLVED] How to parse sections?


blufish

Recommended Posts

I want to know how to parse this... I know there is a way, please help me.

Someone posts:

 

[1]Section 1[/1]

Blah Blah Blah

[1]Section 2[/1]

Blah Blah Blah

[1]Section 3[/1]

 

What I want to do is take all the text inbetween the [1]s and [/1]s and put it into an array, like:

 

$array1 = "Section 1";

$array2 = "Section 2";

$array3 = "Section 3";

 

Then I need the text to be made into something like this.

 

[1]Section 1=Section 1[/1]

Blah Blah Blah

[1]Section 2=Section 2[/1]

Blah Blah Blah

[1]Section 3=Section 3[/1]

 

How can this be done?

 

Thanks

Link to comment
Share on other sites

Well, you could use preg_match to detect all the items between [1] and [/1] and you could then use Str_Replace to find all those variables and replace them. If str_replace doesn't work, try preg_replace instead. The main difference is preg_replace let's you use RegEx. This naturally slows it down so see which one suits your needs

Link to comment
Share on other sites

Try this out, not sure if that's what you wanted though.

 

$input = <<<html
[1]Section 1[/1]
Blah Blah Blah
[1]Section 2[/1]
Blah Blah Blah
[1]Section 3[/1]
html;

preg_match_all("#\[1\](.+)\[/1\](.*[^\[1\]]*)#i", $input, $matches);
$sections = array();
for($i = 0; $i < count($matches[1]); $i++){
$sections[] = array("title" => $matches[1][$i], "content" => trim($matches[2][$i]));
}

echo "<pre>", print_r($sections), "</pre>";

Link to comment
Share on other sites

Okay, in that case then, this should work:

 

$input = <<<html
[1]Section 1[/1]
Blah Blah Blah
[1]Section 2[/1]
Blah Blah Blah
[1]Section 3[/1]
html;

preg_match_all("#\[1\](.+)\[/1\]#i", $input, $matches);
$sections = array();
for($i = 0; $i < count($matches[1]); $i++){
$sections[] = $matches[1][$i];
}

echo "<pre>", print_r($sections), "</pre>";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.