将代码从JavaScript转换为PHP

Convert code from JavaScript to PHP

本文关键字:PHP 转换 JavaScript 代码      更新时间:2024-01-29

我的代码存在一些类似"<i585>"的东西。我想要从"I"到">"的字符串。并将"585"替换为"<i585>"。我用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>

但我必须将这些代码转换为php。所以我写了这个代码

$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;

但这不起作用。

抱歉英语不好。

也许是赛前准备?

$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;

变量名($sonindex-$sonindex)有一些拼写错误。

从原始字符串中删除3个字符,然后在下一次迭代之前,在$start中添加加1,但应该减去1。

$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;