Regular expressions question

4 replies
Hey everyone,

I'm trying to figure out how to write a regular expression that can find a hyperlink that contains a specific word somewhere in the link.

For example, lets say the word is "Product". It should find links like <a href="Products.html"> OR <a href="Product_List.php"> but NOT links like <a href="SomeOtherPage.html">, of course.

I found out how to use Regex to find regular hyperlinks by using href="(?<Link>.*?)"

But I don't know how to make it find hyperlinks that contain a specific word.

So, any regex pros out there know how to do this?
#expressions #question #regular
  • Profile picture of the author iamscottj
    $string1 = "Hello World\n";
    if ($string1 =~ m/rld$/) {
    print "$string1 is a line or string ";
    print "that ends with 'rld'\n";
    }

    This matches whether the string ends with 'rld'... I think this kind of Regex will be used... We are near to the result... I have tried to get some more of it... But couldnt. Please update if you get the answer.
    Signature
    Watch TV Shows Online

    Its beggars pride that he is not a thief.
    {{ DiscussionBoard.errors[2407132].message }}
    • Profile picture of the author ronperkins
      Try this:

      <?php
      $url = "myproductsite.com";
      $pattern = "/product/";
      if (preg_match($pattern, $url)) {
      echo $url;
      }
      ?>
      {{ DiscussionBoard.errors[2408025].message }}
      • Profile picture of the author Brandon Tanner
        Hey guys,

        Sorry, I should have been more clear... I was looking for just plain regex (not language specific). Anyways, I got someone else to help me figure it out. This is what we came up with...

        href="(?<Link>((?!"|product).)*product.*?)"

        Seems to work perfectly. Thanks for the help anyways guys!
        Signature

        {{ DiscussionBoard.errors[2408592].message }}
        • Profile picture of the author iamscottj
          Originally Posted by Brandon Tanner View Post

          Hey guys,

          Sorry, I should have been more clear... I was looking for just plain regex (not language specific). Anyways, I got someone else to help me figure it out. This is what we came up with...

          href="(?<Link>((?!"|product).)*product.*?)"

          Seems to work perfectly. Thanks for the help anyways guys!
          Oops I missed that one. Sorry. Will try to be better next time. Thanks...
          Signature
          Watch TV Shows Online

          Its beggars pride that he is not a thief.
          {{ DiscussionBoard.errors[2411069].message }}

Trending Topics