Jump to content

URL Regular Expression Pattern


gaza165

Recommended Posts

// Pattern and pregmatches etc \\

			$pattern = "%http://\S+\.(?:jpe?g|png|gif)%i";
			$match = preg_match_all($pattern, $body, $matches,1);
			$gaz = $body;	
			$i = 0;	

				foreach($matches[0] as $url) {	
					$replacement = "%TOKEN".$i."%";	
					$gaz = preg_replace("@$url@", $replacement, $gaz, 1);
					$i++;
				}	

				// End of replace with Tokens!! \\	

			$string = nl2br(htmlentities($gaz));
			$i= 0;

				foreach($matches[0] as $value) {
					$replace = "<img src='".$value."'></img>";
					$search = "%TOKEN".$i."%";
				    $string = str_replace($search, $replace, $string);
					$i++;
				}


			$linkpattern = "/http:\/\/[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
			$linkmatch = preg_match_all($linkpattern, $body, $linkmatches,1);
			$i = 0;	

				foreach($linkmatches[0] as $linkurl) {	
					$replacement = "<a href='".$linkurl."'>$linkurl</a>";	
					$new = preg_replace("@$linkurl@", $replacement, $string, 1);
					$i++;
				}	


			echo $new; //output the blog...

 

I am creating a blog that can search for image links and urls for example

 

http://www.domain.com/image1.jpg and http://www.google.com

 

Can someone look at these two patterns and tell me if they are the right ones to use to filter out IMAGE URLS from REGULAR URLS.

 

Thanks

 

Garry

Link to comment
https://forums.phpfreaks.com/topic/119751-url-regular-expression-pattern/
Share on other sites

The images could be expanded if needed. For example, do you need to look for bmps? As for the URLs, it seems overcomplicated to me. If you only want domains, use a similar approach: http://\S+\.[a-z]+\b. I would also add the \b to the end of the images pattern so something like "http://www.domain.com/images.gifs/1.gif" will not half-match.

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.