0

How would I make a regex to extract urls from a page where I am matching to a center part of a url

For example my urls to match would be something like:

http://m2.imageserver.net/media/thumb/66177422433.jpg http://m4.imageserver.net/media/thumb/21717623342.jpg http://m1.imageserver.net/media/thumb/12327722433.jpg

And I want to match by just the imageserver.net/media section of the url as the sub domain may change.

8
  • are they links or plain text?
    – zerkms
    Aug 7, 2013 at 2:50
  • strpos($haystack, $needle) seems to be an easier approach
    – Raptor
    Aug 7, 2013 at 2:50
  • Better than what? Why do you think there is a browser application?
    – zerkms
    Aug 7, 2013 at 2:52
  • @zerkms links in a crawled page.
    – ian
    Aug 7, 2013 at 2:54
  • Use dom and xpath then //a/@href[contains(., "imageserver.net/media")] :-)
    – zerkms
    Aug 7, 2013 at 2:56

3 Answers 3

1

Your regex would be http://[a-zA-Z0-9]+.imageserver.net+[a-zA-Z0-9/]+.jpg.

Advice: Before trying out on code, please check using regexpal. It's basically a javascript regex tester.

Update: Adding a delimiter:

$match_pattern = "#http:\/\/[a-zA-Z0-9]+.imageserver.net+[a-zA-Z0-9\/]+.jpg#";
preg_match_all($match_pattern,$string_to_be_matched,$url_array);
2
  • That gives me a: Warning: preg_match_all(): Delimiter must not be alphanumeric or backslash in /Users/user/Dropbox/localhost/PHPCrawl_081/test.php on line 61
    – ian
    Aug 7, 2013 at 2:59
  • @ian: How about adding a delimiter? Have you made a research on how to work with regexes in php?
    – zerkms
    Aug 7, 2013 at 3:00
0

I have try this one for you. maybe it can help you though.

$text = "http://m2.imageserver.net/media/thumb/66177422433.jpg";

$text = preg_match("/imageserver.net\/media/", $text, $match);

print_r($match);

If I totally understand your question this might be the answer.

3
  • And the $match array will be a bunch of 'imageserver.net/media' strings
    – zerkms
    Aug 7, 2013 at 3:04
  • yes but if you output the $text it shows 1 or true if there is a match.
    – shark
    Aug 7, 2013 at 3:05
  • read the question once again - OP needs to extract urls
    – zerkms
    Aug 7, 2013 at 3:06
0

I don't use regex much but I think this might work.

$string = "jjYy5nhttp://m2.imageserver.net/media/thumb/66177422433.jpgru56rtjr";

    $pattern = "/http:\/\/[^0-9a-zA-Z_ -].imageserver.net\/media\/(.*?).jpg/";
    if (@preg_match_all(${pattern}, ${string}, $matches) ) {
       print $matches['0'];
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.