WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a similar way to select / perform DOM manipulation on the server-side (PHP) like the way jQuery works?

For example, if I wanted to modify content of each <pre class="raw">...</pre> elements inside of a post content, in jQuery you can easily capture them all with:

//In jQuery, this will obtain a collection of <PRE> elements with class "raw":
$("pre.raw").each( function(index,tag) {
    //Modify content of each PRE tags here...
    tag.innerHTML = tag.innerHTML.replace( ..., ... );

In PHP however, I'm trying to do this by adding a filter to "the_content", which will then do some string replacements only inside each of those <pre class="raw"> elements.

Does WordPress already have some built-in utility method to grab elements this way? Or does some 3rd party PHP script exists that will do this?

share|improve this question
up vote 2 down vote accepted

You may also take a look at phpQuery.

share|improve this answer
Muuuuuuuuuuuuuuuuuuch better! Thanks! – bigp Nov 21 '11 at 18:41
Unfortunately, it doesn't preserve the XML self-closing tags when parsing the string. – bigp Nov 21 '11 at 19:06
If this is a problem for you, you may consider Tidy with hide-endtags option – marcochiesi Nov 21 '11 at 19:36

Answering to myself (and perhaps some other developers curious about this question), there is a PHP server-side script that can manipulate the DOM just like jQuery can:


Althought the syntax isn't exactly the same (doesn't use the dollar $ sign as the jQuery object), the functionality works basically the same.

Example (taken from the above link):

$html = file_get_html('http://www.google.com/');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';
share|improve this answer
Replacing content in the $element->innertext property seems to discard all the new-line characters... NO GOOD! :( – bigp Nov 21 '11 at 19:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.