Page 1 of 1

Help with Perl Compatible Regular Expression

Posted: Sat Aug 24, 2002 3:33 am
by Takuma
Hi, I have a file which contain these string:- {CONTENT} or {TITLE} etc. I created the regular expression to find these strings:-

Code: Select all

/\{{$template_variable}\}/
(I think this is right... but not sure) $template_vairable contains CONTENT etc. Now after finding out it has the string I need to replace it with an string like "Hello" etc. I used preg_replace() but can't work out how to use them (I've read the manual...). Please help.

Posted: Sat Aug 24, 2002 3:59 am
by volka
you're looking for complete strings? no wildcards etc?
then you may consider using str_replace. The syntax is almost the same for preg_replace.

The first parameter (search) is what you're looking for (in your case "{CONTENT}"or "{TITLE}") and the second (replace) what you'd like it to be replaced by ("Hello" or "goodbye" or ...). The last parameter (subject) is the source for searching. The result is returned, subject-string not altered.

Any occurence of <search> in <subject> will be replaced. In case of preg_replace the whole matching substring is replaced.

Each parameter may be an array of strings.
Any occurence of one string in the <search>-array is replaced by the corresponding entry in the <replace>-array (in each()-order). If you have less entries in <replace> than in <search> '' is used (the substring is deleted).
This will be done for all strings in <subject>.

Code: Select all

<?php
$search = array('&#123;CONTENT&#125;', '&#123;TITLE&#125;');
$replace = array('Hello', 'goodbye');

$subject = array(
			'You say &#123;TITLE&#125; and I say &#123;CONTENT&#125;',
			'&#123;CONTENT&#125; &#123;CONTENT&#125;',
			'I don''t know why you say &#123;TITLE&#125;, I say &#123;CONTENT&#125;',
			'&#123;CONTENT&#125; &#123;CONTENT&#125;',
			'I don''t know why you say &#123;TITLE&#125;, I say &#123;CONTENT&#125;.'
		);

$subject = str_replace($search, $replace, $subject);
print('<pre>'); print_r($subject); print('</pre>');
?>

Posted: Sat Aug 24, 2002 4:37 am
by Takuma
Thanks again volka but what would be the most fastest way to replace these string?

Posted: Sat Aug 24, 2002 8:56 am
by volka
I put the source of this page in a file eight times and used it as source for str_replace and preg_replace.
$search = array('!{CONTENT}!', '!{TITLE}!'); (without ! for str_replace)
$replace = array('Hello', 'goodbye');

average elapsed time:
0.0468119382858 str_replace
0.0571789741516 preg_replace

Posted: Sat Aug 24, 2002 2:20 pm
by hob_goblin
str_replace is alot faster, and easier to use.. it just doesnt have regular expressions, so it doesnt have to startup the regular expression engines... its for replacing more concrete things

Posted: Sat Aug 24, 2002 2:29 pm
by Takuma
thanks guys... (girls?)