Jump to content

Preg_match image source than remove entire image tag from html


casbboy

Recommended Posts

I have a table with rows of small bits of html code.

I have already set it up to look for each row that has an image in the code like so

<img src="http://www.site.com/file.jpg" width="80" height="90">

I need to create a program with preg_match and preg_replace that will first find the image file's source and then remove the entire image tag.

the image tags can be slightly different. some have the '/' at the end and some come with alt tags.

How can I do this? I need to get the source then remove the whole thing entirely.

Thanks
Ryan
Link to comment
Share on other sites

[code]
<pre>
<?php

$tests = array(
'<img>',
'<img src="1.jpg">',
'<img src="1.gif"/>',
'<img src="abc.png" />',
'<img alt="image" src="1a.gif">',
'abc<img src="1.jpg">123',
'abc<img src="1.jpg">123<img alt="image" src="1a.gif" />xyz',
);

$sources = array();

foreach ($tests as $test) {
echo 'Original: ' . htmlentities($test), '<br/>';
while (preg_match('/<img(.*?)>/', $test, $matches)) {
if (preg_match('/src="(.+?)"/', $matches[1], $source_matches)) {
array_push($sources, $source_matches[1]);
echo 'Source: ', $source_matches[1], '<br/>';
}
$test = preg_replace('/' . preg_quote($matches[0], '/') . '/', '', $test);
}

echo 'After: ' . htmlentities($test), '<br/><br/>';
}

echo 'Sources: ', '<br/>';
print_r($sources);
?>
</pre>
[/code]

[quote]
Original: <img>
After:

Original: <img src="1.jpg">
Source: 1.jpg
After:

Original: <img src="1.gif"/>
Source: 1.gif
After:

Original: <img src="abc.png" />
Source: abc.png
After:

Original: <img alt="image" src="1a.gif">
Source: 1a.gif
After:

Original: abc<img src="1.jpg">123
Source: 1.jpg
After: abc123

Original: abc<img src="1.jpg">123<img alt="image" src="1a.gif" />xyz
Source: 1.jpg
Source: 1a.gif
After: abc123xyz

Sources:
Array
(
    [0] => 1.jpg
    [1] => 1.gif
    [2] => abc.png
    [3] => 1a.gif
    [4] => 1.jpg
    [5] => 1.jpg
    [6] => 1a.gif
)
[/quote]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.