- [php] 특정 문자가 포함돼있는지 확인하는법 목차
반응형
php에서 특정 문자가 포함돼있는지 확인하는 방법을 알아보겠습니다.
1. str_contains 함수입니다.
str_contains(string $haystack, string $needle): bool
첫번째 매개변수에 두번째 매개변수가 포함돼있는지 여부를 bool로 바로 return을 해주는 함수입니다.
<?php
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}
if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}
?>
2. strpos 함수를 이용한 방법입니다.
strpos(string $haystack, string $needle, int $offset = 0): int|false
첫번째 매개변수에서 두번째 매개변수가 몇번째 index에 나오는지 return해주는 함수입니다.
이걸 이용해서 함수를 만들어줍니다.
function contains($str, $text){
return (strpos($str, $text) !== false);
}
이렇게 하면 1번과 같은 결과를 보여주는 함수를 만들수있습니다.
감사합니다.
'개발' 카테고리의 다른 글
[CHAT GPT] chat gpt api사용해보기 - 2 (이미지) (0) | 2023.05.23 |
---|---|
[CHAT GPT] chat gpt api사용해보기 (0) | 2023.05.22 |
[php] 숫자를 한글로 바꾸기 345 -> 삼백사십오 (0) | 2023.05.18 |