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
https://forums.phpfreaks.com/topic/133475-solved-how-to-parse-sections/
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

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>";

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>";

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.