String Replacement with PHP - urgent.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
battman21
Forum Newbie
Posts: 3
Joined: Sun Aug 04, 2002 12:57 am

String Replacement with PHP - urgent.

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

you might want to take a look at the regular expression support of PHP.
perl compatible regular expressions
preg_replace
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post 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.
battman21
Forum Newbie
Posts: 3
Joined: Sun Aug 04, 2002 12:57 am

Post by battman21 »

Thanks heaps for your responses.. i am about to try them out. These look perfect though - wish me luck!

Thanks again,
Post Reply