1

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.

2
  • I'd look into DOM and XPath. I'll whip up a quick demo soon Commented Mar 27, 2013 at 4:40
  • Thanks phill. Consider above codes as string like $str1 = 1st code, $output = 2nd code. Commented Mar 27, 2013 at 4:42

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

use regex to perform such replacements...

Comments

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.