开发者

Apply changes to one string based on differences from another

In PHP, I have two strings:

$str1 = 'amare';

... and ...

$str2 = 'laudare';

For $str2, there is an additional form which is ...

$form2 = 'laudant';

Now I would like to generate $form1 (for $str1) according to the change which was done from $str2 to $form2:

laudare -> laudant =====> amare -> amant

Can you help me to build a function which does that?

<?php
function generateForm($str1, $str2, $form2) {
    // 1) get the shared part of $str开发者_JAVA技巧2 and $form2: "lauda"
    // 2) extract the according part for $str1: "ama"
    // 3) get the ending which has been suffixed: "nt"
    // 4) add the ending from step 3 to the base from step 2: "amant"
    // 5) return the string from step 4
}
?>

How can one implement this in PHP? Thanks a lot in advance!


function generateForm($str1, $str2, $form2) {
$p1=str_split($str2);
$p2=str_split($form2) ;
$i=0;
while($p1[$i]==$p2[$i])
{
  $i++ ;
}

$pre=strlen( substr($str2,$i));

$rep=substr($form2,$i);
return substr($str1,0,(strlen($str1)-$pre)).$rep;
}

this will work but not all the cases


Here you go, but it only works if last letters are changed:

function generateForm($str1, $str2, $form2) {
    $commonStr = '';
    for($i = 0;$i < strlen($str2); $i++){
        if($str2{$i} == $form2{$i}){
            $commonStr .= $str2{$i};
        }
        else
            break;
    }
    $suffix1 = substr($str2, strlen($commonStr));
    $suffix2 = substr($form2,strlen($commonStr));

    $str1common = substr($str1, 0, strlen($str1)-strlen($suffix1));

    return $str1common . $suffix2;
}


<?php

function generateForm($str1, $str2, $form2) {
$str2Ar = preg_split('//', $str2, -1);
$form2Ar = preg_split('//', $form2, -1);
$match = '';
    foreach($str2Ar as $key=>$c)
    {
        if($c == $form2Ar[$key])
        $match .= $c;
        else
        break;
    }
    $pre = substr($str1,0,3);
    $sufix = substr($form2,strlen($form2)-2,2);
    $return_form = $match.$sufix;
    $return_according = $pre.$sufix;
    return array($return_form,$return_according);

}

$str1 = 'amare';
$str2 = 'laudare';
$form2 = 'laudant';

$result = generateForm($str1, $str2, $form2) ;
    echo $result[0];//return form
    echo "<hr>";
    echo $result[1];//return according
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜