lithium\util\String::extract PHP Method

extract() public static method

Extract a part of a string based on a regular expression $regex.
public static extract ( string $regex, string $str, integer $index ) : mixed
$regex string The regular expression to use.
$str string The string to run the extraction on.
$index integer The number of the part to return based on the regex.
return mixed
    public static function extract($regex, $str, $index = 0)
    {
        if (!preg_match($regex, $str, $match)) {
            return false;
        }
        return isset($match[$index]) ? $match[$index] : null;
    }

Usage Example

 /**
  * Tests the `String::extract()` regex helper method.
  */
 public function testStringExtraction()
 {
     $result = String::extract('/string/', 'whole string');
     $this->assertEqual('string', $result);
     $this->assertFalse(String::extract('/not/', 'whole string'));
     $this->assertEqual('part', String::extract('/\\w+\\s*(\\w+)/', 'second part', 1));
     $this->assertNull(String::extract('/\\w+\\s*(\\w+)/', 'second part', 2));
 }