Skip to content

Instantly share code, notes, and snippets.

@kijtra
Last active January 14, 2016 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kijtra/c70fff47422d20955a05 to your computer and use it in GitHub Desktop.
Save kijtra/c70fff47422d20955a05 to your computer and use it in GitHub Desktop.
#PHP preg_match Wrapper
<?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...
});
<?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