atticus Posted February 18, 2009 Share Posted February 18, 2009 Hi all, thanks in advance... Here is my issue... I want to parse an HTML page and replace a title that only occurs inside of an <h1> tag. however, I will not always not the exact format. It may be <h1><a.... or <h1 class="... The HTML for the entire page is delivered to the function in one variable: $buffer <?php function callback($buffer) { //I need to search $buffer, find and replace the title that is in between <h1></h1> and return the entire $buffer...the title appears several places in the page, but only the one instance my be changed. $newphrase = str_replace("A title", "$title", $buffer); return $buffer; } Quote Link to comment https://forums.phpfreaks.com/topic/145811-solved-str_replace-only-inside-of-certain-html/ Share on other sites More sharing options...
premiso Posted February 18, 2009 Share Posted February 18, 2009 Is this the only <h1> tag on the site? If so, this should work: <?php $string = "Replace this title <h1 class=foo>Title</h1>"; $replaced = preg_replace("~<h1(.+?)?>(.+?)</h1>~s", '<h1$1>test title</h1>', $string); echo "Original: " . htmlentities($string) . "<br />"; echo "Replaced: " . htmlentities($replaced) . "<br />"; ?> This will not keep the "class" if you wanted to keep that. If you do care if that is kept let me know and I will do some revisions. EDIT: Changed it so it would keep any attribute inside the <h1> tag. This should work for what you need, given that there is only 1 <h1> tag on the site EDIT:EDIT: Changed it to work with or without attributes in the tag. Quote Link to comment https://forums.phpfreaks.com/topic/145811-solved-str_replace-only-inside-of-certain-html/#findComment-765559 Share on other sites More sharing options...
atticus Posted February 18, 2009 Author Share Posted February 18, 2009 thanks man...you rock...I will give it a try Quote Link to comment https://forums.phpfreaks.com/topic/145811-solved-str_replace-only-inside-of-certain-html/#findComment-765569 Share on other sites More sharing options...
atticus Posted February 18, 2009 Author Share Posted February 18, 2009 worked like a charm...thanks Quote Link to comment https://forums.phpfreaks.com/topic/145811-solved-str_replace-only-inside-of-certain-html/#findComment-765573 Share on other sites More sharing options...
premiso Posted February 18, 2009 Share Posted February 18, 2009 thanks man...you rock...I will give it a try One side note to the above. If you want it to just replace the first one, preg_replace's 4th parameter is a limit, change that to 1 and it will only do the first occurrence. As it is now, it will do all h1's inside the document. Quote Link to comment https://forums.phpfreaks.com/topic/145811-solved-str_replace-only-inside-of-certain-html/#findComment-765575 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.