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.

Link to comment
Share on other sites

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

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.