1

I have the following HTML.

<div class="red">Div One</div>
<div class="green">Div Two</div>
<div class="blue">Div Three</div>

What's the best way of replacing the text in the div with the green class?

Also, I need a way of retrieving the contents of a tag by element name (), or element name and class ().

Thanks for your help!

1
  • Is this an input file you're reading, or part of the webpage you're generating with PHP? Commented Jan 29, 2012 at 19:05

2 Answers 2

3

You can use some kind of HTML parser. I'd use DOMDocument or phpQuery.

In the edge case, you can use regex. But I do not recommend this to you!

$html = preg_replace('~(<div class="green">)(.*)(</div>)~', '$1Replacement$2', $html);

if you want to use class green optional, use

$html = preg_replace('~(<div( class="green">|>))(.*)(</div>)~', '$1Replacement$4', $html);
Sign up to request clarification or add additional context in comments.

8 Comments

There are cases where regular expressions is bad, and yes, HTML is not a regular language, but sometimes it's still often preferable to use regex for something as simple as this, instead of loading a heavy XML library.
@Martin what is so bad about using regex for parsing HTML?
@Martin How do I edit the regex so that either <div class="green" or <div> is present?
@user826855: imagine that you'll accidentally add a space after class="green". Everything breaks. That won't happen in HTML parsers.
@user826855: you want to create class green optional?
|
2

jQuery can do it for you

$(".green").empty().html("your new content for div");

and to retrieve content

var content=$(".blue").html();  //retrieves content inside class blue

2 Comments

why would you use .empty when .html replaces the current content with the new itself?
Quentin Its a jQuery @nav_nav .empty is not necessary here but I just wrote it to make clear understanding even while reading only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.