Skip to content

Instantly share code, notes, and snippets.

@chobie
Created September 7, 2010 17:58
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 chobie/568743 to your computer and use it in GitHub Desktop.
Save chobie/568743 to your computer and use it in GitHub Desktop.
<?php
/**
* Text_PatternMatch
* =================
* テキストを適当にマッチング。
*
* Licence: MIT License
* Author : chobie ( http://twitter.com/chobi_e )
* Created_at: 2010-05-18
*
* Useage:
* $data = "[block]somedata[block]";
* $tm = new Text_PatternMatch($data);
* $tm->left_delimiter = "{{";
* $tm->right_delimiter = "}}";
* $result = $tm->match('[block]{{$string}}[block]');
* //array (
* // 'string' => 'somedata',
* //)
*
**/
class Text_PatternMatch{
protected $version = "0.1-alpha";
protected $data;
public $left_delimiter = "{{";
public $right_delimiter = "}}";
public function __construct($data){
$this->data = $data;
}
public function getVersion(){
return $this->version;
}
public function match($pattern){
$head = $tail = "";
trim($pattern,"\r\n");
$result = array();
$regexp = '/' . preg_quote($this->left_delimiter) . '\$(.+?)' . preg_quote($this->right_delimiter) . '/';
preg_match_all($regexp,$pattern,$matches);
$variables = $matches[1];
if($items = preg_split($regexp,$pattern)){
$count = count($items);
$length = strlen($this->data);
$offset = 0;
for($i=0;$i<$count;$i++):
$prefix = $items[$i];
$prefix_length = strlen($prefix);
if($i+1<$count){
$suffix = $items[$i+1];
}else{
break;
}
$suffix_length = strlen($suffix);
for($x=$offset,$lookprefix = false,$looksuffix = false;$x<$length;$x++):
if($lookprefix === false){
if(substr($this->data,$x,$prefix_length) == $prefix){
$lookprefix = $x+$prefix_length;
$x = $lookprefix;
}
}else{
if(substr($this->data,$x,$suffix_length) == $suffix){
$looksuffix = $x;
break;
}
}
$offset = $x;
endfor;
$key = array_shift($variables);
if(!empty($key)){
$result[$key] = substr($this->data,$lookprefix,($looksuffix-$lookprefix));
}
endfor;
return $result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment