formasfunction Posted May 18, 2007 Share Posted May 18, 2007 I'm trying to write a regular expression that will take a chunk of html and modify the body tag but I'm having trouble as this is my first regex attempt. Here's what I have: $_response_body = whatever html I'm feeding in $pattern = '<body \b[^>]*>'; $replacement = '\\1 <div id="top_frame"><div id="nav_bar">text</div><div id="sub_bar">text</div></div>'; echo $_response_body = preg_replace($pattern, $replacement, $_response_body); So I'm hoping that this would take something like <body class="home"> or <body class="main"> and turn them into: <body class="home"><div id="top_frame"><div id="nav_bar">text</div><div id="sub_bar">text</div></div> or <body class="main"><div id="top_frame"><div id="nav_bar">text</div><div id="sub_bar">text</div></div> Thanks in advance. Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/ Share on other sites More sharing options...
taith Posted May 18, 2007 Share Posted May 18, 2007 wow... theres alot of confusion for such a simple switch! lol <?php if(empty($bodytag)) $bodytag='main'; ?> <body class="<?=$bodytag?>"> then on any page you want to change the class, just give $bodytag a value... Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/#findComment-256320 Share on other sites More sharing options...
formasfunction Posted May 18, 2007 Author Share Posted May 18, 2007 Sorry, I don't think I was clear enough. I don't want to change the class of the body, I want to find the opening body tag regardless of whether or not it has a class attached to it and add a chunk of code after it. If it was always a predictable tag (like always just <body> with no class) then I'd use a str_replace and append my new code at the end. Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/#findComment-256388 Share on other sites More sharing options...
effigy Posted May 18, 2007 Share Posted May 18, 2007 /<body[^>]*>/ Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/#findComment-256394 Share on other sites More sharing options...
formasfunction Posted May 18, 2007 Author Share Posted May 18, 2007 Thanks effigy, that works great. Am I doing my backreference correctly in $replacement? Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/#findComment-256412 Share on other sites More sharing options...
effigy Posted May 18, 2007 Share Posted May 18, 2007 Ah, I didn't catch that; you'll need /(<body[^>]*>)/. You don't need both backslashes in the replace, but it'll work. Quote Link to comment https://forums.phpfreaks.com/topic/52012-quick-regex-question/#findComment-256413 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.