Last active
January 14, 2016 03:45
-
-
Save kijtra/c70fff47422d20955a05 to your computer and use it in GitHub Desktop.
#PHP preg_match Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include('Reg.php'); | |
// Set source | |
Reg::in('<img src="abc" title="sample">') | |
// Not Match = skip | |
->match('/href="([^"]*)"/i', function($match) { | |
// ...something... | |
}) | |
// Match | |
->match('/src="([^"]*)" title="([^"]*)"/i', function($match) { | |
// With full matched text (src="abc" title="sample") | |
$this->match('/([a-zA-Z]+)="[^"]*"/', function($match) { | |
// ...something... | |
}); | |
// ...something... | |
}) | |
// Already Matched = skip | |
->match('/title="([^"]*)"/i', function($match) { | |
// ...something... | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Reg | |
{ | |
private $source = null; | |
private $matched = false; | |
public function __construct($source) | |
{ | |
$this->source = $source; | |
} | |
public static function in($source) | |
{ | |
return new self($source); | |
} | |
public function match($reg, Closure $callback) | |
{ | |
if ($this->matched) { | |
return $this; | |
} | |
if (preg_match($reg, $this->source, $match)) { | |
$this->matched = true; | |
$source = $match[0]; | |
array_shift($match); | |
$class = new self($source); | |
$callback = $callback->bindTo($class); | |
$callback($match); | |
} | |
return $this; | |
} | |
public function source() | |
{ | |
return $this->source; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment