将代码从JavaScript转换为PHP
Convert code from JavaScript to PHP
我的代码存在一些类似"<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;
相关文章:
- 使用Javascript将PHP转换为HTML5
- 如何将JSON从PHP转换为JS
- 将PHP转换为JavaScript,自调用函数
- 从sqlite PHP转换数据
- 注意:将数组从 php 转换为 javascript 时出现数组到字符串的转换错误
- 使用 PHP 转换 SQL 时间
- 如何将其从PHP转换为JavaScript
- 将数组从php转换为javascript
- php转换为javascript并返回
- 将jsonencode php转换为javascript,但不要使用双引号
- 将PHP转换为javascript #1
- 将逗号php转换为javascript
- 用PHP转换知名文本(WKT)从MySQL到谷歌地图多边形
- 将javascript数组从PHP转换为javascript函数
- 通过PHP转换XML &Javascript函数
- 将数学方程式从PHP转换为Javascript (Jquery)
- 使用php转换为json
- 如何将格式日期从PHP转换为Javascript
- 如何将这个PHP转换为express.js/node
- 用于转换从 PHP 转换的序列号的 JavaScript 代码