Home > Software engineering >  how to use str_repalce to repalce string inside function?
how to use str_repalce to repalce string inside function?

Time:09-04

this assignment is solved , but i really not know why some people here are aggressive with new developers and just press the down arrow to reduce reputation points ? #####################

I have assignment to write a php function to replace in a string with specific word and return true if any replace occurred, otherwise return false o Function take two parameters ( string , word )

i write this simple code :

    $artical = "i am php developer" ; 

function check ($word, $new_word,$artical  ) { 

 str_replace ($word , $new_word , $artical , $i ) ;

if ($i > 1 ) { 

    echo " replace is done" ;
}else { 
    echo " no replace is done" ;

}

}

check ('developer' , 'magic' , $artical) ;

but it always gives me "no replace is done " .

can please tell me what is wrong ?

CodePudding user response:

The "str_replace" method replaces all occurrences of the search string with the replacement string. It takes 3 parameters: "Search", "Replace" and "Subject", and an optional parameter "Count".

The search term is $word, the replace term is $new_word and the subject term is "i am a php developer". The count will return the number of words that have been replaced.

Your if statement if ($i > 1 ) returns "no replace is done" if i = 1. It should be changed to if ($i > 0 ).

Your code is successfully replacing the string $artical, but your if statement is giving you the wrong information.

CodePudding user response:

it solved by change if ($i > 1 ) to if ($i > 0 )

$artical = "i am php developer" ; 

function check ($word, $new_word,$artical  ) { 

 str_replace ($word , $new_word , $artical , $i ) ;

if ($i > 1 ) { 

    echo " replace is done" ;
}else { 
    echo " no replace is done" ;

}

}

check ('developer' , 'magic' , $artical) ;
  • Related