- Regex to remove an HTML tag and its content from PHP string
- Example
- How to retain only specified tags
- Example
- Lorem Ipsum
- How to remove certain tags with all their content
- Example
- Example
- Related Articles
- strip_tags
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Примечания
- Смотрите также
- PHP strip_tags() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- PHP strip_tags
- Introduction to the PHP strip_tags() function
- PHP strip_tags() function examples
- 1) Using PHP strip_tags() function to remove all HTML tags
- 2) Using PHP strip_tags() function with some allowed tags
- Summary
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 IpsumLorem 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 IpsumLorem 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 IpsumLorem 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 IpsumLorem 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.
Related Articles
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 .
Смотрите также
PHP strip_tags() Function
The strip_tags() function strips a string from HTML, XML, and PHP tags.
Note: HTML comments are always stripped. This cannot be changed with the allow parameter.
Note: This function is binary-safe.
Syntax
Parameter Values
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
allow | Optional. Specifies allowable tags. These tags will not be removed |
Technical Details
Return Value: | Returns the stripped string |
---|---|
PHP Version: | 4+ |
Changelog: | As of PHP 5.3.4, this function ignores self-closing XHTML tags (like ) in allow parameter As of PHP 5.0, this function is binary-safe. As of PHP 4.3, HTML comments are always stripped. |
More Examples
Example
Strip the string from HTML tags, but allow tags to be used:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
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 ) : string
Code 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)