Forum Moderators: coopster

Message Too Old, No Replies

Search and Replace Script?

         

Acid_Reign

7:03 am on Apr 3, 2005 (gmt 0)

10+ Year Member



Hey, new guy with a quick question. I've almost finished this webpage that I'm making for someone, but I'm killing myself trying to get the last element I need to make it functional work correctly.

What I need to do is change all instances (though there's only one) of the occurance

<td class="maincenter" vAlign="top"> ... </td>

in my code to


<div id="maincenter"> ... </div>

I wasn't sure whether to use JS or PHP; I've looked into string and preg replaces, but I can't seem to get either to work.

Feedback is greatly appreciated.

wrightee

10:31 am on Apr 3, 2005 (gmt 0)

10+ Year Member



Voila:

$s="Other stuff<td class=\"maincenter\" vAlign=\"top\">Contents of block</td>Other Stuff";
$s=preg_replace("#<td class=\"maincenter\" vAlign=\"top\">(.*[^</td>])</td>#","<div id=\"maincenter\">\\1</div>",$s);
echo $s;

This will work if you're sure that your formatting of the replace string is exactly as described - i.e. it won't check for optional spacing, case irregularity etc etc.

killroy

10:52 am on Apr 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you want to do this replace retrospectivly on html already output, you might want to look into autput buffering where you can capture what is beeing written out, apply your regex and then send only the result to the browser.

SN

Acid_Reign

5:07 pm on Apr 3, 2005 (gmt 0)

10+ Year Member



Thanks wrightee, but what if I "don't know" what's inside the block? i.e., its content changes frequently and I want whatever is in there to be wrapped as a division rather than table data.

Output buffering sounds like it might be more of what I wanted to do; how would I go about solving my problem in that respect?

killroy

6:46 pm on Apr 3, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well It would be something like:

ob_start();
//Many PHP Statements outputting HTML
$HTMLSoFar=ob_get_contents();
ob_end_clean();

Now you apply your regexes on $HTMLSoFar and then simply:

echo $HTMLSoFar;

Acid_Reign

9:27 pm on Apr 3, 2005 (gmt 0)

10+ Year Member



Ah, well the search script will probably be the only php on the site, so I don't think I'll need that, but thanks anyway.

I've just spent about 4 or 5 straight hours tampering with my code, and I'm still as lost as ever. I'm trying to teach myself how to do it, but attempting to interpret the PHP Manual into plain English never ceases to give me a headache.

I would post my faulty code, but I doubt it would serve any good seeing as it's all just experimental. Basically, when I'm not getting an error, my output either just adds another block (rather than rewriting the original), or it leaves me with no markup whatsoever.

Suffice it to say, I'm very confused.