Thursday, September 3, 2015

string replace in php manually

<?php
function matching ($string, $matching_word) {
    $length_first = strlen($string);
    $length_second = strlen($matching_word);
    for($i = 0; $i < $length_first; $i++){
        for($j = 0; $j < $length_second; $j++){
            if($string[$i + $j] == $matching_word[$j]){
                if($j == $length_second - 1){
                    return  $i;
                }
            } else{
                break;
            }

        }
    }
    return -1;
}


$string = 'bangladesh is our home land';
$length_string = strlen($string);
$matching_word = 'home';
$length_matching_word = strlen($matching_word);
$replace_word = 'native';
$length_replace_word = strlen($replace_word);
$new_string = "";

$index = matching($string, $matching_word);

if($index == -1){
echo 'replace_word not found';
}else{

for($i = 0; $i < $index; $i++){
   $new_string .= $string[$i];
}
for($k = 0; $k < $length_replace_word; $k++){
   $new_string .= $replace_word[$k];
}
$index = $index + $length_matching_word;
for($l = $index; $l < $length_string; $l++){
   $new_string .= $string[$l];
}

echo $new_string;
}

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }