Gau*_*rav 29 php indexof lastindexof
在Java中,我们可以使用indexOf和lastIndexOf.由于PHP中不存在这些函数,因此PHP代码的PHP等价物是什么?
if(req_type.equals("RMT"))
pt_password = message.substring(message.indexOf("-")+1);
else
pt_password = message.substring(message.indexOf("-")+1,message.lastIndexOf("-"));
Run Code Online (Sandbox Code Playgroud)
Alf*_*Bez 42
您需要以下函数才能在PHP中执行此操作:
strpos找到字符串中第一次出现子字符串的位置
strrpos找到字符串中最后一个子字符串出现的位置
substr返回字符串的一部分
这是substr函数的签名:
string substr ( string $string , int $start [, int $length ] )
Run Code Online (Sandbox Code Playgroud)
substring函数(Java)的签名看起来有点不同:
string substring( int beginIndex, int endIndex )
Run Code Online (Sandbox Code Playgroud)
substring(Java)期望将end-index作为最后一个参数,但substr(PHP)需要一个长度.
在PHP中获取结束索引并不难:
$sub = substr($str, $start, $end - $start);
Run Code Online (Sandbox Code Playgroud)
这是工作代码
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
Run Code Online (Sandbox Code Playgroud)
Mah*_*bub 16
在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;
Run Code Online (Sandbox Code Playgroud)
输出:拳头指数= 2最后一个指数= 13
小智 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83391 次 |
| 最近记录: |