2015-01-08 2 views
0

Чтобы быть более точным, я должен быть в состоянии Газа HTML-теги, как хорошо, как делает этот сценарий: zubrag.com/tools/html-tags-stripper.phpПреобразование HTML страницу в формате обычного текста с помощью PHP

I должны быть в состоянии сделать это на моем локальном хосте (XAMPP сервер) с любым URL, но сейчас я хотел бы использовать этот адрес, чтобы лишить теги, так как это, как messiest он может получить: http://static.anaf.ro/static/10/Timis/Timis.htm

Я do have, не работает, и я не знаю, почему и как его исправить. Вот были код приходит от: nadeausoftware.com/articles/2007/09/php_tip_how_strip_html_tags_web_page

Я добавил эту строку в код, но он все равно не будет работать ...

$text = file_get_contents('http://static.anaf.ro/static/10/Timis/Timis.htm'); 

Ниже исходный код (обратите внимание, что исходный код не имеет линии сверху. Эта линия была добавлена ​​мной)

/** 
* Copyright (c) 2008, David R. Nadeau, NadeauSoftware.com. 
* All rights reserved. 
* See: 
* http://nadeausoftware.com/articles/2007/09/php_tip_how_strip_html_tags_web_page 
*/ 


$text = file_get_contents('http://static.anaf.ro/static/10/Timis/Timis.htm'); 

function strip_html_tags($text) 
{ 
    // PHP's strip_tags() function will remove tags, but it 
    // doesn't remove scripts, styles, and other unwanted 
    // invisible text between tags. Also, as a prelude to 
    // tokenizing the text, we need to insure that when 
    // block-level tags (such as <p> or <div>) are removed, 
    // neighboring words aren't joined. 
    $text = preg_replace(
     array(
      // Remove invisible content 
      '@<head[^>]*?>.*?</head>@siu', 
      '@<style[^>]*?>.*?</style>@siu', 
      '@<script[^>]*?.*?</script>@siu', 
      '@<object[^>]*?.*?</object>@siu', 
      '@<embed[^>]*?.*?</embed>@siu', 
      '@<applet[^>]*?.*?</applet>@siu', 
      '@<noframes[^>]*?.*?</noframes>@siu', 
      '@<noscript[^>]*?.*?</noscript>@siu', 
      '@<noembed[^>]*?.*?</noembed>@siu', 

      // Add line breaks before & after blocks 
      '@<((br)|(hr))@iu', 
      '@</?((address)|(blockquote)|(center)|(del))@iu', 
      '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', 
      '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', 
      '@</?((table)|(th)|(td)|(caption))@iu', 
      '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', 
      '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', 
      '@</?((frameset)|(frame)|(iframe))@iu', 
     ), 
     array(
      ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 
      "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", 
      "\n\$0", "\n\$0", 
     ), 
     $text); 

    // Remove all remaining tags and comments and return. 
    echo strip_tags($text); 
} 
+0

Итак, где же вызов 'strip_html_tags ($ your_text)' и какой результат? Кроме того, вы считаете, что вы показали нам только определение функции? И не показывал вызов функции? –

+0

Я забыл упомянуть, что я не знаю php .. Я просто новичок. html-страница для преобразования в обычный текст будет ссылкой, включенной в вопрос, который является http://static.anaf.ro/static/10/Timis/Timis.htm, кроме этого, я не знаю, что должно быть включено в код ... это на самом деле то, что я надеюсь получить помощь ... некоторые диррекции как минимум – user656931

+1

Тогда советую вам прочитать руководство - http://php.net/manual/en/language.functions.php –

ответ

0

Он отлично работает, но регулярное выражение по ссылке в вашем посте не Работа. Она не возвращает правильный набор символов, так что попробуйте это:

function strip_html_tags($text) 
{ 
    $text = preg_replace(
     array(
      // Remove invisible content 
      '@<head[^>]*?>.*?</head>@siu', 
      '@<style[^>]*?>.*?</style>@siu', 
      '@<script[^>]*?.*?</script>@siu', 
      '@<object[^>]*?.*?</object>@siu', 
      '@<embed[^>]*?.*?</embed>@siu', 
      '@<applet[^>]*?.*?</applet>@siu', 
      '@<noframes[^>]*?.*?</noframes>@siu', 
      '@<noscript[^>]*?.*?</noscript>@siu', 
      '@<noembed[^>]*?.*?</noembed>@siu', 
      // Add line breaks before and after blocks 
      '@</?((address)|(blockquote)|(center)|(del))@iu', 
      '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', 
      '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', 
      '@</?((table)|(th)|(td)|(caption))@iu', 
      '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', 
      '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', 
      '@</?((frameset)|(frame)|(iframe))@iu', 
     ), 
     array(
      ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 
      "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", 
      "\n\$0", "\n\$0", 
     ), 
     $text); 
    return strip_tags($text); 
} 

/* Read an HTML file */ 
$raw_text = file_get_contents('http://static.anaf.ro/static/10/Timis/Timis.htm'); 

/* Get the file's character encoding from a <meta> tag */ 
preg_match("/<meta[^>]+charset=['\"]?(.*?)['\"]?[\/\s>]/i", $raw_text, $matches); 
$encoding = $matches[1]; 

/* Convert to UTF-8 before doing anything else */ 
$utf8_text = iconv($encoding, "utf-8", $raw_text); 

/* Strip HTML tags and invisible text */ 
$utf8_text = strip_html_tags($utf8_text); 

/* Decode HTML entities */ 
$utf8_text = html_entity_decode($utf8_text, ENT_QUOTES, "UTF-8"); 
echo $utf8_text; 

Что я изменил:

Чтобы получить правильную кодировку, я просто заменил это

/* Get the file's character encoding from a <meta> tag */ 
preg_match('@<meta\s+http-equiv="Content-Type"\s+content="([\w/]+)(;\s+charset=([^\s"]+))[email protected]', $raw_text, $matches); 
$encoding = $matches[3]; 

с этим

preg_match("/<meta[^>]+charset=['\"]?(.*?)['\"]?[\/\s>]/i", $raw_text, $matches); 
$encoding = $matches[1]; 

EDIT 1: Gue s у сценария с веб-сайта есть некоторые проблемы с удалением тегов из предоставленного вами URL-адреса. Это показывает много. Я думаю, что лучший способ стримить теги - просто удалить все между открытием < и первым закрытием>. Но я не имею никакого представления о регулярном выражении на данный момент, может быть, google может помочь :)

+0

nice исправить ... можем ли мы добавить некоторые разрывы строк к этому, чтобы сделать контент доступным для чтения? P.S извините за отложенный ответ, я пытался изучить функции :) – user656931

 Смежные вопросы

  • Нет связанных вопросов^_^