Advertisement
gg-master

Генерация списка ссылок на таблицы с помощью регулярок.

Apr 11th, 2024
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | Help | 0 0
  1. function generateTableIndex(&$html)
  2. {
  3.     /*
  4.     Автоматически сформировать “Указатель таблиц”. Работает как оглавление, но
  5.     ссылки делаются на таблицы в документе. Текст ссылки такой:
  6.     Таблица <номер> “содержимое первой ячейки из таблицы”
  7.     */
  8.  
  9.     // Находим все таблицы в HTML
  10.     preg_match_all('/<(table\b[^>]*)>/sui', $html, $tables);
  11.  
  12.     $indexList = '<ul>';
  13.    
  14.     foreach ($tables[1] as $index => $tableHead) {
  15.         $tableId = 'table_' . ($index + 1);
  16.  
  17.         $pattern = '/<' . preg_quote($tableHead, '/') . '>(.*?)<\/?table.*>/s';
  18.        
  19.         preg_match($pattern, $html, $matches);
  20.         $table_content = $matches[0]; // извлечение найденного содержимого таблицы
  21.  
  22.         // Находим содержимое первой ячейки таблицы
  23.         preg_match('/<t[drh][^>]*>(.*?)<\/t[drh]>/is', $table_content, $firstCell);
  24.         $firstCellContent = trim(strip_tags($firstCell[1])); // Получаем текст из ячейки без HTML-тегов
  25.         // print_r($firstCellContent);
  26.  
  27.         // Добавляем ссылку на таблицу в индекс
  28.         $indexList .= '<li><a href="#' . $tableId . '">Таблица ' . ($index + 1) . ' "' . $firstCellContent . '"</a></li>';
  29.  
  30.         $rep_smpl = '/<' . preg_quote($tableHead, '/') . '>/';
  31.         $rep_on = '<' . $tableHead . ' id="' . $tableId . '">';
  32.         // Добавляем идентификатор таблицы для якоря
  33.         $new_table_content = preg_replace($rep_smpl, $rep_on, $table_content, 1);
  34.  
  35.         $html = str_replace($table_content, $new_table_content, $html);
  36.     }
  37.  
  38.     $indexList .= '</ul>';
  39.  
  40.     return $indexList;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement