- Извлечение данных с помощью регулярных выражений PHP
- Текст из скобок
- Результат:
- Текст из HTML тегов
- Результат:
- URL из текста
- Результат:
- href из ссылок
- Результат:
- Анкоры ссылок
- Результат:
- Src из тегов img
- Результат:
- E-mail адреса из текста
- Результат:
- Цвета
- HEX/HEXA
- Результат:
- RGB/RGBA
- Регулярные выражения. Поиск ссылок
- Как получить все ссылки со страницы регулярными выражениями?
- PHP: Parsing HTML to find Links
- Simplest Case
- Room for Extra Attributes
- Allow for Missing Quotes
- Refining the Regexp
- spaces around the = after href:
- matching only links starting with http:
- single quotes around the link address:
- Using the Regular Expression to parse HTML
- First checking robots.txt
- Translations
- References
- Related Articles — Parsing files
Извлечение данных с помощью регулярных выражений PHP
Получение данных с помощью функций preg_match() и preg_match_all() .
Текст из скобок
Извлечение содержимого из круглых, квадратных и фигурных скобок:
$text = ' Телеобъектив: диафрагма [ƒ/2.8] Широкоугольный объектив: (диафрагма ƒ/1.8) По беспроводной сети: Поддержка диапазона: '; /* [. ] */ preg_match_all("/\[(.+?)\]/", $text, $matches); print_r($matches[1]); /* (. ) */ preg_match_all("/\((.+?)\)/", $text, $matches); print_r($matches[1]); /* */ preg_match_all("/\<(.+?)\>/", $text, $matches); print_r($matches[1]); /* */ preg_match_all("/\<(.+?)\>/", $text, $matches); print_r($matches[1]);
Результат:
Array ( [0] => ƒ/2.8 ) Array ( [0] => диафрагма ƒ/1.8 ) Array ( [0] => до 13 часов ) Array ( [0] => Dolby Vision и HDR10 )
Текст из HTML тегов
$text = ' Тег H1
Текст 1
Текст 2
'; /* */ preg_match('/]*?>(.*?)/si', $text, $matches); echo $matches[1]; /* */ preg_match('/]*?>(.*?)/si', $text, $matches); echo $matches[1]; /* Извлекает текст из всех
*/ preg_match_all('/
]*?>(.*?)/si', $text, $matches); print_r($matches[1]);
Результат:
Тег TITLE Тег H1 Array ( [0] => Текст 1 [1] => Текст 2 )
URL из текста
$text = 'Text http://ya.ru text http://google.ru text.'; preg_match_all('/(http:\/\/|https:\/\/)?(www)?([\da-z\.-]+)\.([a-z\.])([\/\w\.-\?\%\&]*)*\/?/i', $text, $matches); print_r($matches[0]);
Результат:
Array ( [0] => http://ya.ru [1] => http://google.ru )
href из ссылок
$text = ' Яндекс Google Mail.ru '; preg_match_all('//i', $text, $matches); print_r($matches[1]);
Результат:
Array ( [0] => http://ya.ru [1] => http://google.ru [2] => http://mail.ru )
Анкоры ссылок
$text = ' Яндекс Google Mail.ru '; preg_match_all('/(.*?)/i', $text, $matches); print_r($matches[1]);
Результат:
Array ( [0] => Яндекс [1] => Google [2] => Mail.ru )
Src из тегов img
$text = 'text text'; preg_match_all('//is', $text, $matches); print_r($matches[1]);
Результат:
E-mail адреса из текста
$text = 'text admin@mail.ru text text text admin@ya.ru'; preg_match_all('/([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]/i', $text, $matches); print_r($matches[0]);
Результат:
Array ( [0] => admin@mail.ru [1] => admin@ya.ru )
Цвета
HEX/HEXA
$css = ' body < color: #000; background: #4545; >header < color: #111111; background: #00000080; >'; preg_match_all('/#(?:[0-9a-f])/i', $css, $matches); print_r($matches[0]);
Результат:
Array ( [0] => #000 [1] => #4545 [2] => #111111 [3] => #00000080 )
RGB/RGBA
$css = ' body < color: rgb(0,0,0); background: rgba(17,85,68,0.33); >header < color: rgb(17,17,17); background: rgba(0,0,0,0.5); >'; preg_match_all('/((rgba)\((\d,\s?)(1|0?\.?\d+)\)|(rgb)\(\d(,\s?\d)\))/i', $css, $matches); print_r($matches[0]);
Array ( [0] => rgb(0,0,0) [1] => rgba(17,85,68,0.33) [2] => rgb(17,17,17) [3] => rgba(0,0,0,0.5) )
Регулярные выражения. Поиск ссылок
От автора: приветствую вас, друзья. Из этой статьи вы узнаете, как с помощью регулярных выражений найти в тексте все ссылки и что-то сделать с ними. Например, мы можем их просто вырезать. Или заменить на что-то свое. В общем, с помощью регулярных выражений мы вольны сделать со ссылками в тексте буквально что угодно. Начнем?
Итак, у нас есть некий текст, в котором, как вы видите ниже, есть пара ссылок.
Теперь нам необходим решить классическую задачу в PHP — найти и, скажем, заменить все ссылки на некий текст. Давайте, как обычно, начнем с составления регулярного выражения, которое найдет все ссылки в данном массиве текста. Ну а затем разберем составленный шаблон регулярного выражения.
Вариант шаблона может выглядеть так:
Онлайн курс «PHP-разработчик»
Изучите курс и создайте полноценный проект — облачное хранилище файлов
С нуля освоите язык программирования PHP, структурируете имеющиеся знания, а эксперты помогут разобраться с трудными для понимания темами, попрактикуетесь на реальных задачах. Напишете первый проект для портфолио.
Как видим, он отработал корректно и все ссылки были найдены. Давайте теперь разберем его.
«[^>]+»> — эта часть совпадает со значением атрибута href. Обратите внимание, внутри символьного класса — [] — мы использовали уже знакомый нам метасимвол ^, который в начале шаблона означает начало строки. Однако в начале символьного класса метасимвол ^ уже означает отрицание, т.е. в данном случае мы говорим, что в кавычках может быть любой символ (один и более), кроме >. В итоге две озвученные части шаблона совпадут со следующей строкой — ;
.+? — эта часть шаблона совпадет с анкором ссылки. Здесь есть уже знакомая нам конструкция — .+ — точка совпадает с любым символом, а квантификатор + позволяет найти 1 и более таких символов. А что за вопросительный знак? Он делает наш шаблон нежадным. Попробуйте убрать его и посмотрите, что получится в итоге;
— последняя часть шаблона совпадет с закрывающим тегом ссылки. Здесь мы обязательно экранируем слеш, поскольку слеш использован нами в качестве ограничителей шаблона. Если бы в качестве ограничителей мы использовали, к примеру, # — необходимости в экранировании слеша не было бы.
Теперь осталось просто заменить найденные ссылки на то, что нам нужно.
Все получилось! Это был простейший пример. На самом деле регулярные выражения позволяют гораздо более гибко решать задачу. Например, мы можем заменить только анкор (текст ссылки). Или только URL ссылки, оставив анкор нетронутым. Больше о регулярных выражениях вы можете узнать из нашего курса по регулярным выражениям.
Онлайн курс «PHP-разработчик»
Изучите курс и создайте полноценный проект — облачное хранилище файлов
С нуля освоите язык программирования PHP, структурируете имеющиеся знания, а эксперты помогут разобраться с трудными для понимания темами, попрактикуетесь на реальных задачах. Напишете первый проект для портфолио.
На этом мы будем завершать сегодняшнюю статью. Удачи!
Как получить все ссылки со страницы регулярными выражениями?
Здравствуйте, скажите пожалуйста как получить все ссылки со страницы регулярными выражениями?
Добавлено через 6 минут
$contents=file_get_contents (trim('http://site.ru/')); echo $contents; ?>
Как убрать http из домена регулярными выражениями
Здравствуйте, уважаемые форумчане. Скажите, как можно убрать из урл вида http://site.ru/ или.
Как найти регулярными выражениями перенос строки?
<tr> <td >Строка 1</td> <td >Строка 2</td> <td >Строка 3</td> <td >Строка 4</td> </tr> .
Работа с регулярными выражениями
Мне нужно получить из страницы определенные куски текста. т.е. надо найти такой кусок <TR.
$contents = file_get_contents("htp://site.ru/"); preg_match_all('/href="([^"]+)"/', $contents, $links); foreach( $links as $key => $link ) echo $link[1]."
";
Сообщение от tolimadokara
$contents = file_get_contents("htp://site.ru/"); preg_match_all('/href="([^"]+)"/', $contents, $links); foreach( $links as $key => $link ) echo $link[1]."
";
качаем phpQuery-onefile.php потом. как фантазия позволяет..
можно так(кусок моего класса для парсинга койчего, не только можно ссылки искать):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
require_once 'phpQuery-onefile.php'; class HtmlParser { private $html; public function __construct($html) { $this->html=$html; } public function getLinks(){ $links=array(); if(!$this->html) return false; $doc = phpQuery::newDocument($this->html); foreach($doc->find('a') as $a){ $buf=trim(pq($a)->text()); if(strlen($buf)==0){ $buf=pq($a)->attr('href'); } $links[pq($a)->attr('href')] = $buf; } return $links; } } ?>
а регулярки я бы использовал для обработки обычных текстов, не содержащих служебных символов. при наличии оных изза экранирования символов регулярка становится нечитаемой. дело вкуса конечно..
PHP: Parsing HTML to find Links
From blogging to log analysis and search engine optimisation (SEO) people are looking for scripts that can parse web pages and RSS feeds from other websites — to see where their traffic is coming from among other things.
Parsing your own HTML should be no problem — assuming that you use consistent formatting — but once you set your sights at parsing other people’s HTML the frustration really sets in. This page presents some regular expressions and a commentary that will hopefully point you in the right direction.
Simplest Case
Let’s start with the simplest case — a well formatted link with no extra attributes:
This, believe it or not, is a very simple regular expression (or «regexp» for short). It can be broken down as follows:
We’re also using two ‘pattern modifiers’:
One shortcoming of this regexp is that it won’t match link tags that include a line break — fortunately there’s a modifer for this as well:
Now the ‘.’ character will match any character including line breaks. We’ve also changed the first space to a ‘whitespace’ character type so that it can match a space, tab or line break. It’s necessary to have some kind of whitespace in that position so we don’t match other tags such as .
For more information on pattern modifiers see the link at the bottom of this page.
Room for Extra Attributes
Most link tags contain a lot more than just an href attribute. Other common attributes include: rel, target and title. They can appear before or after the href attribute:
We’ve added extra patterns before and after the href attribute. They will match any series of characters NOT containing the > symbol. It’s always better when writing regular expressions to specify exactly which characters are allowed and not allowed — 0rather that using the wildcard (‘.’) character.
Allow for Missing Quotes
Up to now we’ve assumed that the link address is going to be enclosed in double-quotes. Unfortunately there’s nothing enforcing this so a lot of people simply leave them out. The problem is that we were relying on the quotes to be there to indicate where the address starts and ends. Without the quotes we have a problem.
It would be simple enough (even trivial) to write a second regexp, but where’s the fun in that when we can do it all with one:
What can I say? Regular expressions are a lot of fun to work with but when it takes a half-hour to work out where to put an extra ? your really know you’re in deep.
Firstly, what’s with those extra ?‘s?
Because we used the U modifier, all patterns in the regexp default to ‘ungreedy’. Adding an extra ? after a ? or * reverses that behaviour back to ‘greedy’ but just for the preceding pattern. Without this, for reasons that are difficult to explain, the expression fails. Basically anything following href= is lumped into the [^>]* expression.
We’ve added an extra capture to the regexp that matches a double-quote if it’s there: (\"??). There is then a backreference \\1 that matches the closing double-quote — if there was an opening one.
To cater for links without quotes, the pattern to match the link address itself has been changed from [^\"]* to [^\" >]*?. That means that the link can be terminated by not just a double-quote (the previous behaviour) but also a space or > symbol.
This means that links with addresses containing unescaped spaces will no longer be captured!
Refining the Regexp
Given the nature of the WWW there are always going to be cases where the regular expression breaks down. Small changes to the patterns can fix these.
spaces around the = after href:
matching only links starting with http:
single quotes around the link address:
And yes, all of these modifications can be used at the same time to make one super-regexp, but the result is just too painful to look at so I’ll leave that as an exercise.
Note: All of the expressions on this page have been tested to some extent, but mistakes can occur in transcribing so please report any errors you may have found when implementing these examples.
Using the Regular Expression to parse HTML
Using the default for preg_match_all the array returned contains an array of the first ‘capture’ then an array of the second capture and so forth. By capture we mean patterns contained in ():
Using PREG_SET_ORDER each link matched has it’s own array in the return value:
If you find any cases where this code falls down, let us know using the Feedback link below.
Before using this or similar scripts to fetch pages from other websites, we suggest you read through the related article on setting a user agent and parsing robots.txt.
First checking robots.txt
As mentioned above, before using a script to download files you should always check the robots.txt file. Here we’re making use of the robots_allowed function from the article linked above to determine whether we’re allowed to access files:
Now you’re well on the way to building a professional web spider. If you’re going to use this in practice you might want to look at: caching the robots.txt file so that it’s not downloaded every time (a la Slurp); checking the server headers and server response codes; and adding a pause between multiple requests — for starters.