My code exist some things like "< i585>". I wan to get string from "i" to ">". And replace "585" instead of "< i585>". I write some code in JavaScript.
<script type="text/javascript">
var foo ="M <i585> <i646>";
while (foo.indexOf("<i") != -1) {
var indexBaş = foo.indexOf("<i");
var indexSon = foo.indexOf(">", indexBaş);
var id = foo.substring(indexBaş + 2, indexSon);
foo = foo.substring(0 , indexBaş) + id + foo.substring(indexSon + 1 , foo.lenght);
}
document.write(foo);
</script>
But I have to convert this code to php. So I write this code
$foo ="M <i585> <i646>";
$start = 0;
$kacTane= 0;
for($i = 0 ; $i < strlen($foo) ; $i++ ) {
if($foo[$i] == "<") {
if(($foo + 1 )< strlen($foo)) {
if($foo[$i+1] == "i") {
$kacTane++;
}
}
}
}
for($i = 0; $i < $kacTane; $i++) {
$ilkIndex = strpos($foo , "<" , $start);
$sonindex = strpos($foo , ">" , $ilkIndex);
$id = substr($foo , $ilkIndex + 2 ,( $sonIndex -3) - $ilkIndex );
$first = substr($foo , 0 , $ilkIndex +2);
$second = substr($foo , $sonIndex + 1 , strlen($foo) - $sonIndex - 1 );
$foo = "$first$id$second";
$start = ($sonindex + 1);
}
echo $foo;
But it isn't work.
Sorry for bad English.
Rikesh
26.5k14 gold badges82 silver badges90 bronze badges
2 Answers 2
Maybe some pregmatch?
$foo ="M <i585> <i646>";
preg_match_all('/<i(.*?)>/',$foo, $results); //search for all numbers
$patterns = array();
$replace = array();
foreach ($results[1] as $result){
$patterns[] = '/<i'.$result.'>/';
switch ($result) {
case '585':
$result = '333';
break;
case '646':
$result = '444';
break;
}
$replace[] = '<i'.$result.'>';
}
$replace = preg_replace($patterns, $replace, $foo); //if you just want to repleace then this single line (+ arrays) are all you need.
echo '<br>'.$replace;
answered Feb 19, 2015 at 12:30
Volvox
1,6491 gold badge12 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
There were some typos with the variable names ($sonindex - $sonIndex).
You remove 3 chars from the original string, then before the next iteration you add plus one to the $start, but you should substract one.
$foo ="M <i585> <i646>";
$start = 0;
$kacTane= 0;
for($i = 0 ; $i < strlen($foo) ; $i++ ) {
if($foo[$i] == "<") {
if(($foo + 1 )< strlen($foo)) {
if($foo[$i+1] == "i") {
$kacTane++;
}
}
}
}
for($i = 0; $i < $kacTane; $i++) {
$ilkIndex = strpos($foo , "<i" ,$start);
$sonIndex = strpos($foo , ">" , $ilkIndex);
$id = substr($foo , $ilkIndex + 2 , $sonIndex - $ilkIndex -2 );
$first = substr($foo , 0 , $ilkIndex );
$second = substr($foo , $sonIndex + 1 , strlen($foo) - $sonIndex - 1 );
$foo = $first.$id.$second;
$start = ($sonIndex - 1);
}
echo $foo;
Comments
default
foreach(). If needed you can convert the array back to string afterwards.for-loop but not using or increasing$ianywhere. Does this function actually stop?