36

Java では、 と を使用できindexOfますlastIndexOf。これらの関数は PHP には存在しないため、この Java コードに相当する PHP は何でしょうか?

if(req_type.equals("RMT"))
    pt_password = message.substring(message.indexOf("-")+1);
else 
    pt_password = message.substring(message.indexOf("-")+1,message.lastIndexOf("-"));
4

4 に答える 4

20

PHPで:

  • stripos()関数は、文字列内で大文字と小文字を区別しない部分文字列が最初に出現する位置を見つけるために使用されます。

  • strripos()関数は、文字列内で大文字と小文字を区別しない部分文字列が最後に出現した位置を見つけるために使用されます。

サンプルコード:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

出力: 最初のインデックス = 2 最後のインデックス = 13

于 2015-09-03T04:57:04.657 に答える
5
<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()
于 2016-06-03T18:36:35.447 に答える