Finding tag through regex

I am saving this for my reference , A post with all commonly used regex, The regex like saving image tags, html links , email validation etc . are one of the most common used regex !

1)   Finding <img> tag through php using regex.

$pattern = ‘/<img[^>]+src[\s='”]’;
$pattern .= ‘+([^”‘>\s]+)/is’;

if(preg_match($pattern,$subject,$match))
{
echo $match[0];
}

2) Find all links in a html page

$input = file(“page.html”);

$regexp = “<as[^>]*href=(“??)([^” >]*?)\1[^>]*>(.*)</a>”;

if(preg_match_all(“/$regexp/siU”, $response, $matches))

6 thoughts on “Finding tag through regex”

  1. I reworked the code somewhat, and the img tag now closes properly. At least if you use my sample code.

    I also enhanced the code somewhat. Firstly, I included the alt attribute. Secondly, the code now collects the result as a variable ($image), that you can use anywhere you like (below the variable $image, that is, of course).

    I don’t know in what context the code is used, so I don’t know how useful my new version is. I’m also not that experienced in writing regular expressions, so I don’t fully understand the original code. It may include needed functionality that is gone in my code.

    $subject = ”;
    $pattern = ‘//’;
    ob_start();
    if(preg_match($pattern,$subject,$match)){
    echo $match[0];}
    $image = ob_get_clean();
    echo $image;

    /matsolof

    PS: If you try my code and don’t see any image, it may be because the image is removed. I’m currently reworking my image pages to flash and remowing all png images.

  2. In my first attempt to comment on the code above, most of my code disappeared for som reason. I make another attempt with some characters represented by html entities

    $subject = ‘Vedum & Uddevalla 2006‘;
    $pattern = ‘/(.*)/’;
    ob_start();
    if(preg_match($pattern,$subject,$match)){
    echo $match[0];}
    $image = ob_get_clean();
    echo $image;

    /matsolof

Leave a Reply