Jump to content

[SOLVED] Splitting a string into one or more arrays


jonathandoe

Recommended Posts

Hi,

 

I have strings submitted by the users of my website in the following format

 

$string = "text goes here

[codetag]some code goes here[/codetag]

more text

[codetag]more code here[/codetag]

... (and so on) ..."

 

and I want to handle the parts of the string inside the [codetag] tags different than the parts outside the tags. What's the best way to do this?

 

I guess one way is to split it into two arrays that on the example above would look like something this:

$texts = ["text goes here\n","\nmore text\n","\n ... (and so on) ..."]

$codes = ["some code goes here","more code here"]

 

How do I do that?

The best way would be to use regex.

 

ex:

 

$text = preg_replace("(\[codetag\](.+?)\[\/codetag])is",'<code>$1</code>', $text);

 

preg_replace() The example will replace all text inside of [codetag][/codetag] with <code>text here</code>

The best way would be to use regex.

 

ex:

 

$text = preg_replace("(\[codetag\](.+?)\[\/codetag])is",'<code>$1</code>', $text);

 

preg_replace() The example will replace all text inside of [codetag][/codetag] with <code>text here</code>

Thanks, but I need to perform at least one more function on each part of the string that are outside the codetags; for example \n\n should be replaced by </p><p>, but not inside the <code> tags.

 

Ie. if $string = "First paragraph.\n\nSecond paragraph.[codetag]Code\n\nA few lines later[/codetag]." then the output should be "First paragraph</p><p>Second paragraph</p><code>Code\n\nA few lines later</code>."

 

... so I guess I need another way to do it.

You can try something like:

 

$string = "First paragraph.\n\nSecond paragraph.[codetag]Code\n\nA few lines later[/codetag].";
$split = preg_split('~\[/?codetag\]~', $string);
for($i = 0;$i < count($split);$i++)
$out .= ($i % 2) ? '</p><code>' . $split[$i] . '</code>' : str_replace("\n\n", '</p><p>', $split[$i]);

echo $out;

Different ways to skin a cat...I suppose an option could include:

 

$string = "First paragraph.\n\nSecond paragraph.[codetag]Code\n\nA few lines later[/codetag].";

function replacement($match){
    $match[0] = str_replace('</p><p>', "\n\n", $match[0]);
    $match[0] = preg_replace('#(?:\[codetag\])(.+?)(?:\[/codetag\])#is', '<code>$1</code>', $match[0]);
    return $match[0];
}

$string = str_replace("\n\n", '</p><p>', $string);
$string = preg_replace_callback('#\[codetag\].+?\[/codetag\]#is', 'replacement', $string);
echo $string;

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.