pushpa
pushpa

Reputation: 151

How to remove only html tags in a string?

I have written code for removing HTML tags, but it is also removing a<b type of strings. I want it to not to remove strings like 2<3 or a<b.

$term="a<b";
echo "Text is--->".preg_replace('/(?:<|&lt;).+?(?:>|&gt;)/', '', $term);

How do I remove html tags in a string, without removing LT or GT?

Upvotes: 10

Views: 38736

Answers (5)

Ali Hesari
Ali Hesari

Reputation: 1939

Remove all HTML tags from PHP string with content!

Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

$srting = '<a title="" href="/index.html"><b>Some Text</b></a> a<b';

echo strip_tags_content($srting);

function strip_tags_content($text) {

    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
    
 }

Output:

a < b

Retrieved from: Remove all html tags from php string

Upvotes: 1

ChangHun Lee
ChangHun Lee

Reputation: 127

Sorry I had not validate enough.

I have checked php5-cli expression below.

(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)

PHP code goes:

#!/usr/bin/php 
<?php

$str = "<html></html>
a<b 1<2 3>1 
<body>1>2</body>
<style file=\"'googe'\" alt=\"google\">hello world</style>
<have a good efghijknopqweryuip[]asdfgghjkzxcv bnm,.me>hello world<> google com</s>
<a se=\"font: googe;\">abcde</a>";

echo "text--->".preg_replace('/(?:<|&lt;)\/?([a-zA-Z]+) *[^<\/]*?(?:>|&gt;)/', '', $str)."\n";

?>

Result:

text--->
a<b 1<2 3>1 
1>2
hello world
hello world<> google com
abcde

Upvotes: 10

ChangHun Lee
ChangHun Lee

Reputation: 127

Strip_tags function is good solution.

But if you need regex, use expression below.

(?:<|&lt;)\/?([a-z]+) *[^\/(?:<|&lt;)]*?(?:>|&gt;)

Upvotes: 1

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Use strip_tags

//If you want to allow some tags
$term = strip_tags($term,"<b>");

Upvotes: -1

user1432124
user1432124

Reputation:

Use strip tags function of php

echo strip_tags($html)

Upvotes: 8

Related Questions