Jump to content

[SOLVED] str_replace only inside of certain HTML.


atticus

Recommended Posts

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;
}


Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.