Regular expressions

Discussion in 'PHP' started by caciocode, Aug 5, 2010.

  1. #1
    I haven't used regular expressions for a long while or PHP. And I can't seem to figure out how to search for a string within an html file and retrieve it using regular expressions.

    Help please.
     
    caciocode, Aug 5, 2010 IP
  2. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #2
    Here is an example:

    <?php
    
    /*	Regular expression example
    	forums.digitalpoint.com		*/
    
    $Html = <<<DP
    <body>
    My name is <span id="name">Alex Roxon</span> and I am a web developer.
    </body>
    DP;
    
    // Perform the regular expression match
    preg_match( '/\<span id\="name"\>([a-zA-Z\s]+)\<\/span\>/', $Html, $Res );
    
    // Output?
    if( ! isset( $Res[1] ) ) exit( "Name not found." );
    else exit( "Name: " . $Res[1] );
    
    ?>
    PHP:
    Some useful functions and documentation: preg_match preg_match_all preg_replace

    You may want to do some reading to better understand regular expression matches, as they are fairly universal in most major languages. This is a good site to start at.
     
    Alex Roxon, Aug 5, 2010 IP
  3. caciocode

    caciocode Peon

    Messages:
    65
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Sorry, that does not answer the question...

    But I found the solution:

    function return_strings_between($text, $openingMarker, $closingMarker) {
        $openingMarkerLength = strlen($openingMarker);
        $closingMarkerLength = strlen($closingMarker);
    
        $result = array();
        $position = 0;
        while (($position = strpos($text, $openingMarker, $position)) !== false) {
          $position += $openingMarkerLength;
          if (($closingMarkerPosition = strpos($text, $closingMarker, $position)) !== false) {
            $result[] = substr($text, $position, $closingMarkerPosition - $position);
            $position = $closingMarkerPosition + $closingMarkerLength;
          }
        }
        return $result;
      }
    
    PHP:
    Usage example:

    $opener = '<a href  href="http:\/\/example/folder.html">';
    $closer = '</a>';
    $users = return_strings_between($page_html, $opener, $closer);
    PHP:
    Thank you.
     
    caciocode, Aug 5, 2010 IP
  4. Alex Roxon

    Alex Roxon Active Member

    Messages:
    424
    Likes Received:
    11
    Best Answers:
    7
    Trophy Points:
    80
    #4
    Perhaps you should have articulated your question better, since that doesn't use regular expressions at all.

    Either way, I'm glad you found a solution.
     
    Alex Roxon, Aug 5, 2010 IP