0

I am trying to replace the words in a string using php. Here i want to replace the words "test php" and "java test" with "new program" and "test program" from the $replacearray array. Note:Here i need to search the words in the string using $searchstring array if matching found it should replace with the $replacearray

The output should be This is new program and test program

Here if my searchstring contains numbers also i want to explode it and seperate the numbers and strings, and want to replace the $string with the exploded string.Here the delimiter i am using is : in $searchstring

Here is my code

 <?php
 $string = "This is test php and java test";
 $searchstring = array('1:test php', '2:java test');
 $replacearray = array('new program', 'test program');

 $replacearraycount = count($replacearray);
 $searchstringcount = count($searchstring);

 for($i = 0; $i < $replacearraycount; $i++) {
     for($i = 0; $i < $searchstringcount; $i++) {
         $string = preg_replace("/".$searchstring[$i]."/", $replacearray[$i], $string, 1);
     }
 }

 echo $string;
 ?>

This is what i am trying by exploding the $searchstring

 <?php
 $string = "This is test php and java test";
 $searchstring = array('1:test php', '2:java test');
 $replacearray = array('test coding','test program');

 $replacearraycount = count($replacearray);
 $searchstringcount = count($searchstring);

 foreach ($searchstring as &$value) {
 $arrid = array();
 $arrname = array();
 foreach (explode(', ', $value) as $el) {
 $ret = explode(':', $el);
 $arrid[$ret[0]] = $ret[0];
 $arrname[$ret[0]] = $ret[1];
 }
 $valueid = $arrid;
 $name = $arrname;

 $finalsearchstring=array();
 array_push($finalsearchstring,$name);
 }

 for($i = 0; $i < $replacearraycount; $i++) {
 $string = preg_replace("/".$finalsearchstring[$i]."/", $replacearray[$i], $string, 1);
 }

 echo $string;
 ?>
2
  • Sorry. I don't get it. What is the question? Jun 20, 2014 at 4:48
  • 2
    Oh. You've used $searchstring[i] and $searchstring[i] while it should be $i instead of just i in both case. Is that a typo in your question? Jun 20, 2014 at 4:50

1 Answer 1

3

If I follow your question, you need one for loop not two and your array index should be $i not just i -

for($i = 0; $i < $replacearraycount; $i++) {
  $string = preg_replace("/".$searchstring[$i]."/", $replacearray[$i], $string, 1);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.