자바의 String.contain() 처럼 php에서도 단어가 포함되었는지 찾는 함수가 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$sentence = '문자열 찾기';
 
$search = '찾기';
 
 
 
if(strpos($sentence , $search)!==false){
 
echo '찾음';
 
} else {
 
echo '못찾음';
 
}
cs



strpos() 는 포함된 단어의 시작 포지션을 리턴해 준다. 주의해야 할 점은 꼭 !== 를 써야한다는 것이다. strpos() 문서에 나와있듯이 함수가 찾는 단어가 없을 경우 FALSE를 리턴 하지만 non-Boolean FALSE를 리턴하는 경우도 있다(포지션이 0인 경우).
















error_reporting(E_ALL);

ini_set("display_errors", 1);












php에서 array_search()는 단일 array에서만 사용이 가능하고 다중 array의 경우에 false를 반환한다.


다음과 같이 foreach를 이용하여 다중 array에서도 사용가능하다.



1
2
3
4
5
6
7
8
9
10
11
12
<?php    
    function searchForId($id$array) {
        foreach ($array as $key => $val) {
            if ($val['uid'=== $id) {
                return $key;
            }
        }
        return null;
    }
 
?>
 
cs




php 5.5이상에서는 다음과 같이 쓰면 된다.


1
2
3
4
<?php    
    $key = array_search('100', array_column($userdb'uid'));
?>
 
cs







php에서는 Java에서 처럼 startWith 이나 endWith 기능을 하는 함수가 없으므로 만들어서 써야한다. 다음과 같이 간단히 쓸 수 있다.



1. 함수



1
2
3
4
5
6
7
function startsWith($haystack, $needle){
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}
 
function endsWith($haystack, $needle){
    return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
cs



2. 결과


startsWith("abcdef", "ab") -> true

startsWith("abcdef", "cd") -> false

startsWith("abcdef", "ef") -> false

startsWith("abcdef", "") -> true

startsWith("", "abcdef") -> false


endsWith("abcdef", "ab") -> false

endsWith("abcdef", "cd") -> false

endsWith("abcdef", "ef") -> true

endsWith("abcdef", "") -> true 

endsWith("", "abcdef") -> false



1. 정규식을 통한 제거


1
$text = preg_replace('/\r\n|\r|\n/','',$text); 
cs




2. 문자열 함수사용으로 제거


1
$text = str_replace(array("\r\n","\r","\n"),'',$text); 
cs

또는


1
$text = strtr($text,array("\r\n"=>'',"\r"=>'',"\n"=>''));
cs


+ Recent posts