Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular expression question

Status
Not open for further replies.

Masali

Programmer
Joined
Jun 19, 2002
Messages
143
Location
SE
Hi,

I have a variable that contains HTML with certain tags like {NEWS}, {DIARY}, {ETC}. So a template could look like this:

Code:
<html>
<head>
<title>Test</title>
</head>
<body>
<table border=&quot;1&quot; cellspacing=&quot;1&quot; width=&quot;100%&quot; id=&quot;AutoNumber1&quot;>
  <tr>
    <td width=&quot;50%&quot;>{NEWS}</td>
    <td width=&quot;50%&quot;>{DIARY}</td>
  </tr>
</table>
</body>
</html>

I want to make a loop that foreach keyword (tag) replaces the tag with the appropriate content. Something like this..

Code:
while($tag=regexpression)
{
$tag=$content[$tag];
}

Please advice

Masali
 
yes, i know that, but the tags will be replaced with different content according to the tagname.. so for every tag there is different content that needs to be prepared when I know the tagname. That's why i want the loop.

I know how to do it in Perl, but I have just started using PHP instead.. This is what I need, but in PHP instead of Perl

Code:
while($template=~/\{(.*)\}/ig)
{
if($1 eq &quot;NEWS&quot;)
{
$1=&quot;The news are...&quot;;
}
elsif($1 eq &quot;DIARY&quot;)
{
$1=&quot;My diary contains...&quot;;
}
}
 
If you hand preg_replace two arrays, it will do exactly what you loop in perl does.

The first element in the search array is replaced with the first element in the replacement array. Etc.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Can you please show me some example code. I don't quite get it..

Masali
 
unashamedly stolen from php.net comments for preg_replace ( - I was looking at this very thing yesterday.)

<?php
$string = &quot;The quick brown fox jumped over the lazy dog.&quot;;

$patterns[0] = &quot;/quick/&quot;;
$patterns[1] = &quot;/brown/&quot;;
$patterns[2] = &quot;/fox/&quot;;

$replacements[2] = &quot;bear&quot;;
$replacements[1] = &quot;black&quot;;
$replacements[0] = &quot;slow&quot;;

print preg_replace($patterns, $replacements, $string);

/* Output
======

The bear black slow jumped over the lazy dog.

*/

/* By ksorting patterns and replacements,
we should get what we wanted. */

ksort($patterns);
ksort($replacements);

print preg_replace($patterns, $replacements, $string);

/* Output
======

The slow black bear jumped over the lazy dog.

*/

?>


______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top