0
4

1 に答える 1

2

正規表現を使用して HTML を解析することが 100% 信頼できるわけではないという通常の免責事項が適用されます。しかし、正規表現に行き詰まっている場合は、次のようにすることができます。

preg_match_all(
    '%<a\b[^<>]*>      # Match an opening <a> tag
    (?:(?!<img\b).)*   # Match any characters except <img> tags
    <img\b[^<>]*>      # Match one <img> tag
    (?:(?!<img\b).)*   # Match any characters except <img> tags
    </a>               # Match a closing <a> tag%sx', 
    $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

単一のタグ (およびオプションの空白) のみを許可する場合はimg、少し簡単になります。

preg_match_all(
    '%<a\b[^<>]*>  # Match an opening <a> tag
    \s*            # Match optional whitespace
    <img\b[^<>]*>  # Match one <img> tag
    \s*            # Match optional whitespace
    </a>           # Match a closing <a> tag%sx', 
    $subject, $result, PREG_PATTERN_ORDER);
于 2013-05-16T07:22:16.837 に答える