Php закрытие всех тегов

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.

Источник

PHP — автоматическое закрытие всех открытых HTML тегов

Все знают, что в административной панели сайта хорошо править контент страниц в визуальном редакторе, который имеет название WYSIWYG. Вот и наш редактор как-то странно себя начал вести, перестал закрывать HTML теги (не все, а те, которые ему хочется). Т.к. JS программист в это время был в отпуске нужно было срочно исправить проблему. Пришлось вставлять костыль в виде скрипта на PHP, которые будет автоматом закрыть все незакрытые теги.

Разработка интернет-магазинов 

Лучшие цены
на
раскрутку и оптимизацию

сайтов

Разработка интернет-магазинов 

Лучшие цены
на
раскрутку и оптимизацию

сайтов

]*>|i", substr($content, $position), $match)) < $tag = strtolower($match[2]); //игнорируем все одиночные теги if (in_array($tag, $ignored_tags) == FALSE) < //тег открыт if (isset($match[1]) AND $match[1] == '') < if (isset($open_tags[$tag])) $open_tags[$tag]++; else $open_tags[$tag] = 1; >//тег закрыт if (isset($match[1]) AND $match[1] == '/') < if (isset($open_tags[$tag])) $open_tags[$tag]--; >> $position += strlen($match[0]); > else $position++; > //закрываем все теги foreach ($open_tags as $tag => $count_not_closed) < $content .= str_repeat("", $count_not_closed); > return $content; > ?>
$text = close_tags($_POST['body_page']);

Источник

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 .

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

Источник

Закрыть открытые HTML-теги в строке

Ситуация – это строка, которая приводит к чему-то вроде этого:

This is some text and here is a bold text then the post stop here.

Поскольку функция возвращает тизер (сводку) текста, он останавливается после определенных слов. Где в этом случае ярлык сильно не закрыт. Но вся строка завернута в абзац.

Можно ли преобразовать приведенный выше результат / вывод в следующее:

This is some text and here is a bold text then the post stop here.

Я не знаю, с чего начать. Проблема в том, что .. Я нашел функцию в Интернете, которая делает это регулярное выражение, но она помещает закрывающий тег после строки .. поэтому он не будет проверяться, потому что я хочу, чтобы все теги open / close в тегах абзаца. Функция, которую я нашел, делает это также неверно:

This is some text and here is a bold text then the post stop here.

Я хочу знать, что тег может быть сильным, курсивом, чем угодно. Вот почему я не могу добавить функцию и закрыть ее вручную в функции. Любой шаблон, который может сделать это для меня?

Вот функция, которую я использовал раньше, которая работает очень хорошо:

function closetags($html) < preg_match_all('#<(?!meta|img|br|hr|input\b)\b([az]+)(?: .*)?(?#iU', $html, $result); $openedtags = $result[1]; preg_match_all('##iU', $html, $result); $closedtags = $result[1]; $len_opened = count($openedtags); if (count($closedtags) == $len_opened) < return $html; >$openedtags = array_reverse($openedtags); for ($i=0; $i < $len_opened; $i++) < if (!in_array($openedtags[$i], $closedtags)) < $html .= ''; > else < unset($closedtags[array_search($openedtags[$i], $closedtags)]); >> return $html; > 

Лично, однако, я бы не сделал этого с помощью regexp, но библиотеки, такой как Tidy. Это будет выглядеть примерно так:

$str = '

This is some text and here is a bold text then the post stop here.

'; $tidy = new Tidy(); $clean = $tidy->repairString($str, array( 'output-xml' => true, 'input-xml' => true )); echo $clean;

Небольшая модификация исходного ответа … в то время как исходный ответ правильно разделил теги. Я обнаружил, что во время моего усечения я мог бы в итоге нарезать теги. Например:

This text has some in it 

Усечение символа 21 приводит к:

Следующий код основывается на следующем лучшем ответе и исправляет это.

function truncateHTML($html, $length) < $truncatedText = substr($html, $length); $pos = strpos($truncatedText, ">"); if($pos !== false) < $html = substr($html, 0,$length + $pos + 1); >else < $html = substr($html, 0,$length); >preg_match_all('#<(?!meta|img|br|hr|input\b)\b([az]+)(?: .*)?(?#iU', $html, $result); $openedtags = $result[1]; preg_match_all('##iU', $html, $result); $closedtags = $result[1]; $len_opened = count($openedtags); if (count($closedtags) == $len_opened) < return $html; >$openedtags = array_reverse($openedtags); for ($i=0; $i < $len_opened; $i++) < if (!in_array($openedtags[$i], $closedtags)) < $html .= ''; > else < unset($closedtags[array_search($openedtags[$i], $closedtags)]); >> return $html; > $str = "This text has bold in it"; print "Test 1 - Truncate with no tag: " . truncateHTML($str, 5) . "
\n"; print "Test 2 - Truncate at start of tag: " . truncateHTML($str, 20) . "
\n"; print "Test 3 - Truncate in the middle of a tag: " . truncateHTML($str, 16) . "
\n"; print "Test 4: - Truncate with less text: " . truncateHTML($str, 300) . "
\n";

Надеюсь, это поможет кому-то.

Существует множество других переменных, которые необходимо решить, чтобы дать полное решение, но не охвачены вашим вопросом.

Однако я бы предложил использовать что-то вроде HTML Tidy и, в частности, методы repairFile или repaireString .

Этот метод PHP всегда работал для меня. Он закроет все незакрытые теги HTML.

function closetags($html) < preg_match_all('#<([az]+)(?: .*)?(?#iU', $html, $result); $openedtags = $result[1]; preg_match_all('##iU', $html, $result); $closedtags = $result[1]; $len_opened = count($openedtags); if (count($closedtags) == $len_opened) < return $html; >$openedtags = array_reverse($openedtags); for ($i=0; $i < $len_opened; $i++) < if (!in_array($openedtags[$i], $closedtags))< $html .= ''; > else < unset($closedtags[array_search($openedtags[$i], $closedtags)]); >> return $html; > 

Использование регулярного выражения не является идеальным подходом для этого. Вместо этого вы должны использовать html-парсер для создания допустимой объектной модели документа.

В качестве второго варианта, в зависимости от того, что вы хотите, вы можете использовать регулярное выражение для удаления любых тэгов html из вашей строки, прежде чем поместить их в

.

Я сделал этот код, ведь ты справляешься с работой совершенно правильно …

Это старая школа, но эффективная, и я добавил флаг для удаления незавершенных тегов, таких как «blah blah http: // stackoverfl»

public function getOpennedTags(&$string, $removeInclompleteTagEndTagIfExists = true) < $tags = array(); $tagOpened = false; $tagName = ''; $tagNameLogged = false; $closingTag = false; foreach (str_split($string) as $c) < if ($tagOpened && $c == '>') < $tagOpened = false; if ($closingTag) < array_pop($tags); $closingTag = false; $tagName = ''; >if ($tagName) < array_push($tags, $tagName); >> if ($tagOpened && $c == ' ') < $tagNameLogged = true; >if ($tagOpened && $c == '/') < if ($tagName) < //orphan tag $tagOpened = false; $tagName = ''; >else < //closingTag $closingTag = true; >> if ($tagOpened && !$tagNameLogged) < $tagName .= $c; >if (!$tagOpened && $c == ' <') < $tagNameLogged = false; $tagName = ''; $tagOpened = true; $closingTag = false; >> if ($removeInclompleteTagEndTagIfExists && $tagOpened) < // an tag has been cut for exemaple ' blabh blah return $tags; > 
$tagsToClose = $stringHelper->getOpennedTags($val); $tagsToClose = array_reverse($tagsToClose); foreach ($tagsToClose as $tag) < $val .= ""; > 

если установлен модуль в порядке, используйте расширение php tidy:

Источник

Читайте также:  Python traceback что это
Оцените статью