Jeyasithar
Jeyasithar

Reputation: 213

PHP function to remove String without HTML tags in the given html

I have a html code:

<a href="#">foo</a>bar is dummy string<p>hello</p>

I want an output to be

<a href="#">foo</a><p>hello</p>

I am searching for PHP code to get the above result. Filter only html embedded strings to output. I know strip_tags() function will remove html tags and output only the strings.

Upvotes: 1

Views: 856

Answers (3)

Roni
Roni

Reputation: 70

Let's take your html code in $html

$string = strip_tags($html); 
$final = str_replace($string , "", $html); 

It may helps you. Someone answered the same and unfortunately he has deleted.

Thanks

Upvotes: 0

Phil
Phil

Reputation: 164766

Try this

$html = <<<_HTML
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<a href="#">foo</a>bar is dummy string<p>hello</p>
</body>
</html>
_HTML;

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$textNodes = $xpath->query('/html/body/a/following-sibling::text()[1]');
if ($textNodes->length) {
    $node = $textNodes->item(0);
    $node->parentNode->removeChild($node);
}
echo '<pre>', htmlspecialchars($doc->saveHTML()), '</pre>';

Result is

<!DOCTYPE html>
<html><head><title>Test</title></head><body>
<a href="#">foo</a><p>hello</p>
</body></html>

Demo here - http://codepad.viper-7.com/akDqkj

Upvotes: 2

Desolator
Desolator

Reputation: 22759

use regex to perform such replacements...

Upvotes: -1

Related Questions