Jump to content

REGEX help... need modification


mitov

Recommended Posts

Hi everyone,

 

This is my current code snippet:

 

	{

	function replaceImage( &$row, $autoresize, $maxchars, $width = 0, $height = 0 ) {
		global $database, $_MAMBOTS, $current_charset;
		$image = "";
		$regex = "/\<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>/";
		preg_match ($regex, $row->text, $matches);
		$images = (count($matches)) ? $matches : array();
		if (count($images)) $image = $images[1];

		if ($image) {
			if ($autoresize && function_exists('imagecreatetruecolor') 
				&& ($image1 = modJaSLWI::processImage ( $image, $width, $height ))) {
					$image = 'background:url('.JURI::base().$image1.') no-repeat;';
			} else {
					$image = 'background:url('.JURI::base().$image.') no-repeat;';
        }

 

 

I need to make it only process images which have a number in the file name, for example demo2.jpg and not demo.jpg. I think editing the regex and/or the preg_match may do it? It's a wild guess... am i totally wrong?

 

Thank in advance!

Link to comment
https://forums.phpfreaks.com/topic/143829-regex-help-need-modification/
Share on other sites

A simple example:

 

$str = '<img src = "demo2.jpg" />'; // play aorund with this...
$regex = '#<img.+?src\s*=\s*([\'"])[^0-9\1]+\1[^/>]*/?>#i';
if(preg_match($regex, $str)){
   echo 'No numbers found!';
} else {
   echo 'Error! number(s) found!';
}

 

Just a note on this regex:

$regex = "/\<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>/";

 

Using .* or .+ is very inefficient and should be used only in really well controlled circumstances (this situation not being one of them)... make it a lazy quantifier .*? or .+? instead at the very least.

Aslo note, you don't have to escape characters like > in a character class...

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.