Reputation: 465
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;
?>
Upvotes: 0
Views: 50
Reputation: 201537
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);
}
Upvotes: 3