Php тег удаляющий html

Regex to remove an HTML tag and its content from PHP string

We use the in-built PHP strip_tags() function to remove HTML, XML, and PHP tags from a PHP string.

Example

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

"; echo strip_tags($mystring);

Lorem IpsumLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

As you can see, it removes all the HTML tags and their attributes but retains all the content of those tags.

How to retain only specified tags

The strip_tags() function allows for a second optional argument for specifying allowable tags to be spared when the rest HTML tags get stripped off. This way, you can retain some and remove all the other tags.

Example

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

"; echo strip_tags($mystring,"

,

");

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

As you can see the rest of the tags have been removed leaving the string with only the and

, which were specified in the second argument.

How to remove certain tags with all their content

As opposed to the above examples where only tags are removed but their content remains intact, let’s see how we can do away with specific tags together with their content.

To achieve this we use the PHP preg_replace() function.

The first argument is the regular expression(we specify the tag(s) that we want to remove or replace in it), the second is the match(this is what we replace the specified tag(s) with) and the third is the string in which we want to make changes to.

Replace the terms «tag» with the respective opening and closing tags you wish to remove and $str with your string. These tags in the string will get replaced with whatever you set as the second argument, in this case, removed since we have used empty quotes «» .

Example

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

"; echo preg_replace('~~Usi', "", $mystring);

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

We have removed the tag and its content as specified in the function.

If you would like to strip off multiple tags with their content at a go, you can specify them as an array of regular expressions in the first argument of the function.

Example

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec volutpat ligula.

"; echo preg_replace(array('~~Usi','~~Usi','~~Usi'), "", $mystring);

Lorem sit amet, adipiscing elit. Donec nec volutpat ligula.

We have specified an array of , and , all which together with their content have been striped off.

That’s all for this article.

Источник

strip_tags

Эта функция пытается возвратить строку str , из которой удалены все NULL-байты, HTML и PHP теги. Для удаления тегов используется тот же автомат, что и в функции fgetss() .

Список параметров

Второй необязательный параметр может быть использован для указания тегов, которые не нужно удалять.

Замечание:

Комментарии HTML и PHP-теги также будут удалены. Это жестко записано в коде и не может быть изменено с помощью параметра allowable_tags .

Замечание:

Этот параметр не должен содержать пробелов. strip_tags() рассматривает тег как нечувствительную к регистру строку, находящуюся между и первым пробелом или >.

Замечание:

В PHP 5.3.4 и новее также необходимо добавлять соответвующий закрывающий тег XHTML, чтобы удалить тег из str . Например, для удаления и и
нужно сделать следующее:

Возвращаемые значения

Возвращает строку без тегов.

Список изменений

Версия Описание
5.3.4 strip_tags() больше не удаляет соответвующие закрывающие XHTML теги, если они не переданы в allowable_tags .
5.0.0 strip_tags() теперь безопасна для обработки бинарных данных.

Примеры

Пример #1 Пример использования strip_tags()

Результат выполнения данного примера:

Примечания

Из-за того, что strip_tags() не проверяет валидность HTML, то частичные или сломанные теги могут послужить удалением большего количества текста или данных, чем ожидалось.

Эта функция не изменяет атрибуты тегов, разрешенных с помощью allowable_tags , включая такие атрибуты как style и onmouseover, которые могут быть использованы озорными пользователями при посылке текста, отображаемого также и другим пользователям.

Замечание:

Имена тегов в HTML превышающие 1023 байта будут рассматриваться как невалидные независимо от параметра allowable_tags .

Смотрите также

Источник

Strip all HTML tags, except allowed

I’ve seen a lot of expressions to remove a specific tag (or many specified tags), and one to remove all but one specific tag, but I haven’t found a way to remove all except many excluded (i.e. all except p, b, i, u, a, ul, ol, li ) in PHP. I’m far from good with regex, so I’d need a hand. 🙂 Thanks!

3 Answers 3

you can do this by using strip_tags function

¶ strip_tags — Strip HTML and PHP tags from a string

 strip_tags($contant,'tag you want to allow'); 

Thanks for explaining how to exclude multiple tags. The original ducumentation isn’t that clear about this point.

You can use array instead of string starting from php 7.4 $html_value = strip_tags($contente, [‘code’, ‘p’]);

It’s interesting that strip_tags doesn’t have an option to strip the content within non-allowed tags. Would have made the function more versatile.

The php.net/strip_tags page does have a function that does just this. strip_tags_content by mariusz.tarnaski

Why is this the accepted answer. strip_tags() does NOT exactly this! The title says: Strip all HTML tags, »»»»»»except«««««« allowed For strip_tags() it can be specified what to include, NOT what to exclude.

@icefront — you need to learn to read. Quote from the Doc: You can use the optional second parameter to specify tags which should not be stripped. These are either given as string, or as of PHP 7.4.0, as array

@icefront Because it is the answer. Strig_tags accepts second parameter where we can describe tags that should be allowed.

If you need some flexibility, you can use a regex-based solution and build upon it. strip_tags as outlined above should still be the preferred approach.

The following will strips only tags you specify (blacklist):

// tags separated by vertical bar $strip_tags = "a|strong|em"; // target html $html = 'hadf'; // Regex is loose and works for closing/opening tags across multiple lines and // is case-insensitive $clean_html = preg_replace("#]*?>#im", '', $html); // prints "hadf"; echo $clean_html; 

Источник

PHP strip_tags

Summary: in this tutorial, you’ll learn how to use the PHP strip_tags() function to strip HTML and PHP tags from a string.

Introduction to the PHP strip_tags() function

The strip_tags() function returns a new string with all HTML and PHP tags removed from the input string.

Here’s the syntax of the strip_tags() function:

strip_tags ( string $string , array|string|null $allowed_tags = null ) : stringCode language: PHP (php)

The strip_tags() function has the following parameters:

  • $string is the input string.
  • $allowed_tags is one or more tags that you want to retain in the result string. The $allowed_tags can be a string that contains the list of tags to retain e.g.,’p>’. If you use PHP 7.4.0 or later, you can pass an array of tags instead of a string, e.g., [‘div’,’p’] .

PHP strip_tags() function examples

Let’s take some examples of using the strip_tags() function.

1) Using PHP strip_tags() function to remove all HTML tags

The following example shows how to use the strip_tags() function to strip all HTML tags from the contents of the page https://www.php.net:

 $html = file_get_contents('https://www.php.net/'); $plain_text = strip_tags($html); echo $plain_text;Code language: PHP (php)
  • First, use the file_get_contents() function to download the HTML contents from the php.net.
  • Second, strip all the HTML tags from the HTML contents using the strip_tags() function.

2) Using PHP strip_tags() function with some allowed tags

The following example uses the strip_tags() function to strip all HTML tags from the contents of the page https://www.php.net but keeps the following tags: [‘h1’, ‘h2’, ‘h3’, ‘p’, ‘ul’, ‘li’, ‘a’] :

 $html = file_get_contents('https://www.php.net/'); $simple_html = strip_tags($html, ['h1', 'h2', 'h3', 'p', 'ul', 'li', 'a']); echo $simple_html;Code language: PHP (php)

Summary

Источник

Читайте также:  Jquery datatables css cdn
Оцените статью