什么是分割不均匀字符串变量值的最快方法

时间:2013-02-05 15:48:45

标签: php performance parsing html-parsing

我必须拆分这些字符串值,这将是拆分它的最佳算法。

字符串随

而变化
$string=X-1, Sector -12, Dhaka-131301 Landline: +(93)-(220)-5533491, 4390666 Email: sample@tesrting.com

$string =C-1, Sector -00, Dhaka-131301 Landline: 5533491, 4390666 Mobile : 9999999999 Email: sample2@tesrting.com

$string =XC, Sector -12, Dhaka-131301 Mobile: 90909090909

我的代码是

$landlinenumber=array("","","","","");
$address=array("","","","","");
$pincode="";

$ldm=explode('Email:',$string,2);
$ema=$ldm[1];

$ldm=explode('Landline',$ema[0],2);

$adss=explode(',',$ldm[0]);
for($inm=0;$inm<sizeof($adss);$inm++)
{
$pins=trim($adss[$inm]);
$m=preg_match('/[0-9]{6}/', $pins, $matches);
if($m)
{
    $pincode=$matches[0];
    continue;
}
$address[$inm]=$adss[$inm];
}

$ld=explode(':',$ldm[1],2);

if(strpos($ld[1],','))
{
$nums=explode(',',$ld[1]);
for($inm=0;$inm<sizeof($nums);$inm++)
{
    $landlinenumber[$inm]=$nums[$inm];
}

}
elseif(strpos($ld[1],'/'))
{
$nums=explode('/',$ld[1]);
for($inm=0;$inm<sizeof($nums);$inm++)
{
    $landlinenumber[$inm]=$nums[$inm];
}
}
else
{
$landlinenumber[$inm]=$ld[1];
}

1 个答案:

答案 0 :(得分:0)

$string="X-1, Sector -12, Dhaka-131301 Landline: +(93)-(220)-5533491, 4390666 Email: sample@tesrting.com";
testparse( $string );
$string="C-1, Sector -00, Dhaka-131301 Landline: 5533491, 4390666 Mobile : 9999999999 Email: sample2@tesrting.com";
testparse( $string );
$string="XC, Sector -12, Dhaka-131301 Mobile: 90909090909";
testparse( $string );

exit;

function testparse( $str )
{
    if( preg_match('/^(.*), Sector (-[0-9][0-9]), Dhaka-([0-9]+) Landline: (.*) Mobile : ([0-9]+) Email: (.*)$/', $str, $regs ))
        $res = array_combine( array('line', 'code', 'sector','dhaka','landlines','mobile','email'), $regs);
    else if( preg_match('/^(.*), Sector (-[0-9][0-9]), Dhaka-([0-9]+) Landline: (.*) Email: (.*)$/', $str, $regs ))
        $res = array_combine( array('line', 'code', 'sector','dhaka','landlines','email'), $regs );
    else if( preg_match('/^(.*), Sector (-[0-9][0-9]), Dhaka-([0-9]+) Mobile: ([0-9]+)$/', $str, $regs ))
        $res = array_combine( array('line', 'code', 'sector','dhaka','mobile'), $regs );
    else
        die("Unable to compute:\n$str\n");

    echo "Got: ";
    var_export( $res );
    return $res;
}

请注意第三个字符串在Mobile和冒号之间缺少空格。