Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2005
    Location
    UK, London
    Posts
    762

    simple question about preg_match()

    Hello,

    I am trying to grab some text from an external website and display it on my script. The text i am after is between <td class="description"> and </td>.

    So tried to code it like this:

    PHP Code:
    $lines file_get_contents('http://www.some-site.com/');

    preg_match('/<td class="description">(.*)<\/td>/'$lines$matches);

    print_r($matches); 
    When i run this script, all i am getting is :

    Array ( )
    Where i am i going wrong? Any tips/advice on this would be much appreciated. Thanks.

  2. #2
    Join Date
    May 2007
    Location
    Orange Country, CA
    Posts
    138
    You need to escape the double-quotes in your regex with backslashes (\). Here's more info on formatting strings: http://www.php.net/manual/en/language.types.string.php
    Blesta - Professional Billing Software
    We are about creating good experiences
    Trial - Demo | 866.478.7567 | Twitter @blesta

  3. #3
    Join Date
    Feb 2005
    Location
    Australia
    Posts
    5,842
    No, quotes aren't the problem here. Most likely your match crosses several lines, so you need the s modifier to treat the whole string as a single line.

    Try this:
    PHP Code:
    $lines file_get_contents('http://www.some-site.com/');

    preg_match('|<td class="description">(.*?)</td>|s'$lines$matches);

    print_r($matches); 
    (also changed to use a different delimiter | so you don't need to escape the / in your regexp and to make the match non-greedy with .*?)
    Chris

    "Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them." - Laurence J. Peter

  4. #4
    Join Date
    Apr 2000
    Location
    California
    Posts
    3,051
    Also you might want to do a case insensitive match /i just to be sure, in case it's not all lower case on the site. I'd also recommend having it parse/read line by line, rather than slurping all of the data into a single string before you parse it. Then, you might also want to do global matches, in case the same match is repeated on the same line, if you want more than a single match.

  5. #5
    Join Date
    Mar 2004
    Location
    USA
    Posts
    4,342
    PHP Code:
    $lines file_get_contents('http://www.some-site.com/');

    preg_match('/<td class="description">(.*)<\/td>/ism'$lines$matches);

    print_r($matches); 
    Peace,
    Testing 1.. Testing 1..2.. Testing 1..2..3...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •