2016-06-06 3 views
-4

Как я могу получить, чтобы забрать содержимое внутри альт тег с регулярным выражениемКак получить содержимое внутри alt?

Учитывая этот текст:

<a href="gallery.com/gallery-name"; target="_blank"> <img class="aligncenter" src="myblog.com/wp-content/image.jpg " alt=" I want to get this text " width=" 400 " height="300" /></a>

Как соответствовать I want to get this text

Я попытался это alt=".*" но это дает alt=" I want to get this text " width=" 400 " height="300", что нежелательно.

+0

Если у вас есть код с альт тег, разместить его. –

+0

Вы должны * никогда не анализировать HTML с регулярным выражением. Вместо этого используйте [парсер PHP DOM] (http://simplehtmldom.sourceforge.net/). –

+0

Связанные: http://stackoverflow.com/a/1732454/18356 – shoover

ответ

1

Предисловие

Вы действительно должны использовать HTML-парсер для этого, но вы, кажется, есть творческий контроль над исходной строкой, и если это действительно это просто то крайние случаи должны быть сокращены.

Описание

<img\s(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\salt=['"]([^"]*)['"]?) (?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?>

Regular expression visualization

Это регулярное выражение будет делать следующее:

  • найти все изображения тегов
  • требует тега изображения, чтобы иметь атрибут alt
  • захвата значение alt атрибута и поместить в группу захвата 1
  • позволяет значению быть окруженными в одно-, двух- или без кавычек
  • избежать некоторых довольно сложных случаев краев, которые сделали бы соответствие HTML трудно

Пример

Демо

https://regex101.com/r/cN0lD4/2

Пример текста

Примечание трудный крайний случай во втором img тега.

<a href="gallery.com/gallery-name"; target="_blank"> <img class="aligncenter" src="myblog.com/wp-content/image.jpg" alt=" I want to get this text" width =" 400 " height="300" /></a> 

<img onmouseover=' alt="This is not the droid you are looking for" ;' class="aligncenter" src="myblog.com/wp-content/image.jpg" alt="This is the droid I'm looking for." width =" 400 " height="300" /> 

Образец Матчи

  • Захват группы 0 получает весь img тег
  • Захват группы 1 получает только значение в атрибуте alt, не включая окружающие кавычки
[0][0] = <img class="aligncenter" src="myblog.com/wp-content/image.jpg" alt=" I want to get this text" width =" 400 " height="300" /> 
[0][1] = I want to get this text 

[1][0] = <img onmouseover=' alt="This is not the droid you are looking for" ;' class="aligncenter" src="myblog.com/wp-content/image.jpg" alt="This is the droid I'm looking for." width =" 400 " height="300" /> 
[1][1] = This is the droid I'm looking for. 

Пояснение

NODE      EXPLANATION 
---------------------------------------------------------------------- 
    <img      '<img' 
---------------------------------------------------------------------- 
    \s      whitespace (\n, \r, \t, \f, and " ") 
---------------------------------------------------------------------- 
    (?=      look ahead to see if there is: 
---------------------------------------------------------------------- 
    (?:      group, but do not capture (0 or more 
          times (matching the least amount 
          possible)): 
---------------------------------------------------------------------- 
     [^>=]     any character except: '>', '=' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     ='      '=\'' 
---------------------------------------------------------------------- 
     [^']*     any character except: ''' (0 or more 
           times (matching the most amount 
           possible)) 
---------------------------------------------------------------------- 
     '      '\'' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     ="      '="' 
---------------------------------------------------------------------- 
     [^"]*     any character except: '"' (0 or more 
           times (matching the most amount 
           possible)) 
---------------------------------------------------------------------- 
     "      '"' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
     =      '=' 
---------------------------------------------------------------------- 
     [^'"]     any character except: ''', '"' 
---------------------------------------------------------------------- 
     [^\s>]*     any character except: whitespace (\n, 
           \r, \t, \f, and " "), '>' (0 or more 
           times (matching the most amount 
           possible)) 
---------------------------------------------------------------------- 
    )*?      end of grouping 
---------------------------------------------------------------------- 
    \s      whitespace (\n, \r, \t, \f, and " ") 
---------------------------------------------------------------------- 
    alt=      'alt=' 
---------------------------------------------------------------------- 
    ['"]      any character of: ''', '"' 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
     [^"]*     any character except: '"' (0 or more 
           times (matching the most amount 
           possible)) 
---------------------------------------------------------------------- 
    )      end of \1 
---------------------------------------------------------------------- 
    ['"]?     any character of: ''', '"' (optional 
          (matching the most amount possible)) 
---------------------------------------------------------------------- 
)      end of look-ahead 
---------------------------------------------------------------------- 
    (?:      group, but do not capture (0 or more times 
          (matching the most amount possible)): 
---------------------------------------------------------------------- 
    [^>=]     any character except: '>', '=' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    ='      '=\'' 
---------------------------------------------------------------------- 
    [^']*     any character except: ''' (0 or more 
          times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    '      '\'' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    ="      '="' 
---------------------------------------------------------------------- 
    [^"]*     any character except: '"' (0 or more 
          times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    "      '"' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    =      '=' 
---------------------------------------------------------------------- 
    [^'"\s]*     any character except: ''', '"', 
          whitespace (\n, \r, \t, \f, and " ") (0 
          or more times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
)*      end of grouping 
---------------------------------------------------------------------- 
    "      '"' 
---------------------------------------------------------------------- 
    \s?      whitespace (\n, \r, \t, \f, and " ") 
          (optional (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    \/?      '/' (optional (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    >      '>' 
---------------------------------------------------------------------- 
0

Спасибо тем, кто помог решить это:

'/<img.*?alt="(.*?)".*>/'