Jump to content


Photo

Preg_match image source than remove entire image tag from html


  • Please log in to reply
1 reply to this topic

#1 casbboy

casbboy
  • Members
  • PipPip
  • Member
  • 15 posts

Posted 27 September 2006 - 10:05 PM

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

Again, thanks for all the help I recieve

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 27 September 2006 - 10:37 PM

<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>

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
)


Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users