2014-11-14 3 views
14

자바에서는 indexOflastIndexOf을 사용할 수 있습니다. PHP에 이러한 함수가 존재하지 않기 때문에이 Java 코드와 PHP는 무엇이 맞습니까? PHP에서PHP의 indexOf 및 lastIndexOf?

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

http://php.net/manual/en/function.strstr.php – alu

+0

입니다 JavaScript가 있기 때문에 IndexOf와 LastIndexOf를 사용할 수 있습니다. – Dotnetter

+0

* "PHP에 이러한 함수가 존재하지 않으므로 *"- 검색 했습니까? 지난 번 내가 체크했을 때, PHP는 여전히이 기능을 제공하고있었습니다. 'lastIndexOf'의 이름은''strrpos()'입니다. (http : // php())''indexOf'는 ['strpos()'] (http://php.net/manual/en/function.strpos.php) .net/manual/ko/function.strrpos.php). – axiac

답변

10

:

  • 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

20

당신은 PHP에서이 작업을 수행하기 위해 다음과 같은 기능이 필요합니다 :

strpos 문자열에서 문자열의

substr 반환 부분 문자열이 마지막으로 나타나는 위치를 찾기 문자열

strrpos에서 문자열이 처음 나타나는 위치를 찾기

여기에 substr 함수의 서명이 있습니다.

string substr (string $string , int $start [, int $length ]) 
string substring(int beginIndex, int endIndex) 

substring (자바) 최종 파라미터로 최종 지수 예상되지만 substr (PHP)의 길이를 예상 : 414,substring 함수 (자바)의 서명은 약간 다르다 보인다.

그것은 하드, get the end-index in PHP 아니다 : 여기

$sub = substr($str, $start, $end - $start); 

는 작업 코드를

$start = strpos($message, '-') + 1; 
if ($req_type === 'RMT') { 
    $pt_password = substr($message, $start); 
} 
else { 
    $end = strrpos($message, '-'); 
    $pt_password = substr($message, $start, $end - $start); 
} 
2
<pre> 

<?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 "4" 


//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 "2" 


//so these (above) are the two ways to run a function similar to indexOf and lastIndexOf() 

?> 
</pre>