Jump to content

Take all occurrences of X and save it in an array?


SuperBlue

Recommended Posts

It's easy to get the "Between" content, as long as there's only one occurrence. However i want to search a string for "<tag>Between</tag>" and save the content of each occurrence in an array, i also want to replace the original with. I.E "$a1, $a2, $a3", so that i can replace these easily later.

 

 

I'm trying to deal with user input, and as such, there's the possibility that the user would have multiple code boxes. I'm replacing these with pre tags, this works fine.

 

The problem is, that I'm also doing a nl2br on the input text, this converts all line-breaks into br tags. This interferes with the content of code boxes. Since i cant make nl2br ignore everything between the code tags, i need to temporary replace the line-breaks, and insert them again after nl2br has been run.

 

Or perhaps, write my own function to change the line-breaks, and leave-out/ignore everything between code tags.

<pre>
<?php
$data = <<<DATA
<tag>Between1</tag>
ABC
<tag>Between2</tag>
DEF
<tag>Between3</tag>
DATA;

$array = array();

function custom_func ($matches) {
	global $array;	
	static $count = 0;
	++$count;
	array_push($array, $matches[1]);
	return '$a' . $count;
}

echo preg_replace_callback('%<tag>(.*?)</tag>%', 'custom_func', $data), '<br/>';
print_r($array);
?>
</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.