我的代码存在一些类似“< i585 >”的东西。我想获取从“i”到“">”的字符串。并将“585”替换为“
<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;
关于javascript - 将代码从 JavaScript 转换为 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28605468/