Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace - How to remove contents inside a tag?

Say I have this.

$string = "<div class=\"name\">anyting</div>1234<div class=\"name\">anyting</div>abcd"; 
$regex = "#([<]div)(.*)([<]/div[>])#";
echo preg_replace($regex,'',$string);

The output is abcd

But I want 1234abcd

How do I do it?

like image 949
Kavin Avatar asked Dec 10 '22 06:12

Kavin


2 Answers

Like this:

preg_replace('/(<div[^>]*>)(.*?)(<\/div>)/i', '$1$3', $string);

If you want to remove the divs too:

preg_replace('/<div[^>]*>.*?<\/div>/i', '', $string);

To replace only the content in the divs with class name and not other classes:

preg_replace('/(<div.*?class="name"[^>]*>)(.*?)(<\/div>)/i', '$1$3', $string);
like image 104
sg3s Avatar answered Dec 11 '22 18:12

sg3s


$string = "<div class=\"name\">anything</div>1234<div class=\"name\">anything</div>abcd"; 
echo preg_replace('%<div.*?</div>%i', '', $string); // echo's 1234abcd

Live example:

http://codepad.org/1XEC33sc

like image 32
Pedro Lobito Avatar answered Dec 11 '22 20:12

Pedro Lobito