Skip to content

Instantly share code, notes, and snippets.

@kijtra kijtra/Reg.php
Last active Jan 14, 2016

Embed
What would you like to do?
#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
You can’t perform that action at this time.