Page 1 of 1

String Replacement with PHP - urgent.

Posted: Sun Aug 04, 2002 12:57 am
by battman21
Hey there.. wondering if any one can help..

i have a large block of XML in a file that i wish to search through, find 2 strings (container tags) , then replace the xml in between the containers. I don't really want to have to parse the XML (as i already have it all in a multidimensonal array, but do not want to have to format it all for each container cause there are a lot - i'd rather "cheat" and just replace what i need to)

Any ideas on how to do it? Can PHP's string functions look for 2 strings, and replace what's in between them with what might be a long string?

eg.

<container>
<stuff></stuff>
<i></i>
<need></need>
<replaced></replaced>
</container>

Thanks to anyone who can help.. i really am stressing a little and might be missing something that is probably easy.

Cheers

Posted: Sun Aug 04, 2002 3:51 am
by volka
you might want to take a look at the regular expression support of PHP.
perl compatible regular expressions
preg_replace

Posted: Sun Aug 04, 2002 4:47 am
by gnu2php
If you want to get everything between each <tag> and </tag>, try this:

Code: Select all

<?php

$data = <<<END
<container> 
<stuff></stuff> 
<i></i> 
<need></need> 
<replaced></replaced> 
</container>
END;

$tag_name = 'container';

preg_replace_callback("/<$tag_name>(.*)<\/$tag_name>/iUs", 'callback_func', $data);

// i = Ignore case
// U = Turn off "greediness"
// s = Have dot (.) also search newlines


function callback_func($matches)
&#123;
	// $matches&#1111;1] is what's between the tags

	print "<pre>".htmlentities($matches&#1111;1])."</pre>";

	return $matches&#1111;0]; // The match is replaced with this
&#125;

?>
I use preg_replace_callback() because you get more control when each match is found.

Posted: Sun Aug 04, 2002 7:23 pm
by battman21
Thanks heaps for your responses.. i am about to try them out. These look perfect though - wish me luck!

Thanks again,