-1

I have a div called

 <div id="form">Content</div>

and I want to replace the content of the div with new content using Preg_replace. what Regex should be used.?

vinay035
  • 31
  • 3
  • 6
  • 1
    It's described million times. Don't use Regex to work with HTML. Use DOMDocument or some other HTML parser. – s.webbandit May 06 '12 at 06:57
  • 1
    possible duplicate of [Regular Expression to get contents of div class in php](http://stackoverflow.com/questions/3446766/regular-expression-to-get-contents-of-div-class-in-php) – mario May 06 '12 at 12:27

2 Answers2

0

You shouldn't be using a regex at all. HTML can come in many forms, and you would need to take all of them in account. What if the id/class doesn't come in the place you expect? The regex would have to be really complex to get you reasonable results.

Instead, you should use a DOM parser - or a really cool tool I recently stumbled across, phpQuery. With it, you can access your document in PHP almost exactly as you would with jQuery.

Community
  • 1
  • 1
Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
  • 2
    -1 Dated joke pages don't make good explanation links. (You should read the title at least and past the non-answers somewhen, btw). We certainly have something more reasonable on SO. – mario May 06 '12 at 12:26
  • @mario: I agree that the link is old and tongue-in-cheek, but this is an issue that does not age. I did try to look for a more serious answer but it's pretty difficult because SO doesn't have a "sort by best answer score" search. If you find one feel free to change it. – Kaivosukeltaja May 08 '12 at 04:43
0

This will work in your case:

$html = '<div id="content">Content</div>';
$html = preg_replace('/(<\s*div[^>]*>)[^<]*(<\s*\/div\s*>)/', '$1New Content$2', $html); 
echo $html; // <div id="content">New Content</div>

However note that since HTML is not a regular language it is impossible to handle all cases. The simple regex I provided will produce bad output in the following example:

<div class=">">Content</div>
Paul
  • 139,544
  • 27
  • 275
  • 264