21,886
社区成员
发帖
与我相关
我的任务
分享
array( "86041049"=>"match", "83"=>"not match", "9715"=>"match" );
$tmpl = "86041049799715";
$target = "86041049839715";
$result = strMatch( $tmpl, $target );
// 希望 $result 为 array( "86041049"=>"match", "83"=>"not match", "9715"=>"match" )
function strMatch( $tmpl, $target )
{
// 这里是需要实现的算法
}
class Splitter
{
private function equal( $cTarget, $cTmpl )
{
return $cTarget == $cTmpl;
}
private function merge( $char, $idx )
{
// 临时字符串
$this->segment = $this->segment . $char;
// 如果当前字符的“标志”跟下一个字符的“标志”不一样,则把当前的临时字符串做输出
if ( $idx == count($this->flags)-1 || $this->flags[$idx] != $this->flags[$idx+1] ) {
//$this->result[$this->segment] = $this->flags[$idx] ? 'match' : 'not match';
$this->result[] = array(
'text' => $this->segment,
'match' => $this->flags[$idx]
);
$this->segment = '';
}
}
public function split( $tmpl, $target )
{
// 把“目标字符串”拆解成“目标字符数组”
$chars = str_split($target);
// 把“样板字符串”也拆解成字符数组,并逐个与“目标字符数组”相比较,得到“标志数组”
$this->flags = array_map( array($this, 'equal'), $chars, str_split($tmpl) );
// 用于保存最终的拆分结果
$this->result = array();
// 拆分过程中的临时字符串
$this->segment = '';
// 遍历“目标字符数组”,对相邻的“标志相同”的字符进行合并
array_walk( $chars, array($this, 'merge') );
return $this->result;
}
}
function strMatch( $tmpl, $target )
{
$splitter = new Splitter;
return $splitter->split( $tmpl, $target );
}
$tmpl = "86041049799715";
$target = "86041049839715";
$result = strMatch( $tmpl, $target );
var_dump($result);
array
0 =>
array
'text' => string '86041049' (length=8)
'match' => boolean true
1 =>
array
'text' => string '83' (length=2)
'match' => boolean false
2 =>
array
'text' => string '9715' (length=4)
'match' => boolean true
$tmpl = "86041049799715";
$target = "86041049839715";
$result = strMatch( $tmpl, $target );
// 希望 $result 为 array( "86041049"=>"match", "83"=>"not match", "9715"=>"match" )
print_r($result);
function strMatch( $tmpl, $target ) {
$k = 1;
$t = '';
for($i=0; $i<strlen($tmpl); $i++) {
if(($tmpl{$i} == $target{$i} && $k) || ($tmpl{$i} != $target{$i} && !$k)) {
$t .= $k ? $tmpl{$i} : $target{$i};
}else {
$r[$t] = ($k ? '' : 'no') .'match';
$k ^= 1;
$t = $k ? $tmpl{$i} : $target{$i};
}
}
$r[$t] = ($k ? '' : 'no') .'match';
return $r;
}