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

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.