etc./StackOverFlow

문자열에 특정 단어가 포함되어 있는지 어떻게 확인합니까?

청렴결백한 만능 재주꾼 2021. 11. 9. 00:28
반응형

질문자 :Community Wiki


고려하다:

 $a = 'How are you?'; if ($a contains 'are') echo 'true';

if ($a contains 'are') 문을 작성하는 올바른 방법은 무엇입니까?



다른 문자열 안에서 한 문자열의 발생을 찾는 데 strpos() 함수를 사용할 수 있습니다.

 $a = 'How are you?'; if (strpos($a, 'are') !== false) { echo 'true'; }

!== false 의 사용은 의도적입니다( != false === true 모두 원하는 결과를 반환하지 않음). strpos() 는 건초 더미 문자열에서 바늘 문자열이 시작하는 오프셋을 반환하거나 바늘을 찾을 수 없는 경우 false 0은 유효한 오프셋이고 0은 "거짓"이므로 !strpos($a, 'are') 와 같은 더 간단한 구문을 사용할 수 없습니다.

이제 PHP 8에서는 str_contains를 사용하여 이 작업을 수행할 수 있습니다.

 if (str_contains('How are you', 'are')) { echo 'true'; }

RFC


Community Wiki

다른 사용자가 언급했듯이 strpos 비해 단어 일치에 더 좋기 때문에 정규식을 사용할 수 있습니다. are 대한 strpos 검사는 또한 다음과 같은 문자열에 대해 true를 반환합니다. 요금, 주의, 응시 등. 이러한 의도하지 않은 일치는 단어 경계를 사용하여 정규식에서 간단히 피할 수 있습니다.

are 대한 간단한 일치는 다음과 같을 수 있습니다.

 $a = 'How are you?'; if (preg_match('/\bare\b/', $a)) { echo 'true'; }

성능 측면에서 strpos 는 약 3배 더 빠릅니다. 한 번에 백만 개의 비교를 수행했을 때 preg_match 가 완료되는 strpos 경우 0.5초가 걸렸습니다.

편집: 단어 단위가 아닌 문자열의 모든 부분을 검색하려면 다음과 같은 정규식을 사용하는 것이 좋습니다.

 $a = 'How are you?'; $search = 'are y'; if(preg_match("/{$search}/i", $a)) { echo 'true'; }

정규식 끝에 있는 i 는 정규식을 대소문자를 구분하지 않도록 변경합니다. 원하지 않으면 생략할 수 있습니다.

이제 이것은 $search 문자열이 어떤 식으로든 삭제되지 않기 때문에 어떤 경우에는 상당히 문제가 될 수 있습니다. 즉, $search 가 사용자 입력인 것처럼 어떤 경우에는 검사를 통과하지 못할 수 있습니다. 다른 정규 표현식처럼 행동하십시오 ...

또한 다양한 정규식 Regex101에 대한 설명을 테스트하고 볼 수 있는 훌륭한 도구가 있습니다.

두 기능 세트를 단일 다목적 기능(선택 가능한 대소문자 구분 포함)으로 결합하려면 다음과 같이 사용할 수 있습니다.

 function FindString($needle,$haystack,$i,$word) { // $i should be "" or "i" for case insensitive if (strtoupper($word)=="W") { // if $word is "W" then word search instead of string in string search. if (preg_match("/\b{$needle}\b/{$i}", $haystack)) { return true; } } else { if(preg_match("/{$needle}/{$i}", $haystack)) { return true; } } return false; // Put quotes around true and false above to return them as strings instead of as bools/ints. }

한 가지 더 명심해야 할 점은 \b 는 영어 이외의 다른 언어에서는 작동하지 않는다는 것입니다.

이에 대한 설명과 솔루션은 여기에서 가져옵니다 .

\b 는 단어의 시작 또는 끝(단어 경계)을 나타냅니다. 이 정규식은 사과 파이의 사과와 일치하지만 파인애플, 사과 카트 또는 베이크 사과의 사과와 일치하지 않습니다.

"카페" 어때요? 정규식에서 "café"라는 단어를 어떻게 추출할 수 있습니까? 실제로 \bcafé\b는 작동하지 않습니다. 왜요? "café"에 ASCII가 아닌 문자가 포함되어 있기 때문입니다. é. \b는 समुद्र, , месяц 및 .

유니코드 문자를 추출하려면 단어 경계를 나타내는 문자를 직접 정의해야 합니다.

답: (?<=[\s,.:;"']|^)UNICODE_WORD(?=[\s,.:;"']|$)

따라서 PHP에서 답변을 사용하려면 다음 함수를 사용할 수 있습니다.

 function contains($str, array $arr) { // Works in Hebrew and any other unicode characters // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed // Thanks https://www.phpliveregex.com/ if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true; }

단어 배열을 검색하려면 다음을 사용할 수 있습니다.

 function arrayContainsWord($str, array $arr) { foreach ($arr as $word) { // Works in Hebrew and any other unicode characters // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed // Thanks https://www.phpliveregex.com/ if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true; } return false; }

PHP 8.0.0부터 이제 str_contains를 사용할 수 있습니다.

 <?php if (str_contains('abc', '')) { echo "Checking the existence of the empty string will always return true"; }

Community Wiki

다음은 이와 같은 상황에서 유용한 약간의 유틸리티 기능입니다.

 // returns true if $needle is a substring of $haystack function contains($needle, $haystack) { return strpos($haystack, $needle) !== false; }

Community Wiki

보통이 아니다 당신의 문자열의 하위 문자열이 나타납니다 당신이 문자열 특정 단어를 찾고, 그리고하지 않는 경우 원하는 경우 이러한 답변의 대부분은 당신을 말할 것이다 동안.

차이점이 뭐야? 하위 문자열은 다른 단어 안에 나타날 수 있습니다.

  • "area"의 시작 부분에 있는 "are"
  • "are"는 "hare"의 끝에
  • "운임"의 중간에 "있다"

이를 완화하는 한 가지 방법은 단어 경계 ( \b )와 결합된 정규식을 사용하는 것입니다.

 function containsWord($str, $word) { return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str); }

이 방법에는 위에서 언급한 것과 동일한 오탐지가 없지만 고유한 몇 가지 경우가 있습니다. az , AZ , 0-9 또는 _ 가 아닌 문자가 아닌 문자( \W )에서 일치합니다. 즉, 숫자와 밑줄은 단어 문자로 계산되며 다음과 같은 시나리오는 실패합니다.

  • "무엇을 _are_ 생각하시나요?"의 "are"입니다.
  • "헐"의 "are"가 are4인지도 모릅니다.

이보다 더 정확한 것을 원하면 영어 구문 분석을 시작해야 합니다. 이는 상당히 큰 웜입니다(어쨌든 구문의 적절한 사용을 전제로 하지만 항상 주어진 것은 아닙니다).


Community Wiki

문자열에 다른 문자열이 포함되어 있는지 확인하려면 PHP 함수 strpos() 사용할 수 있습니다.

 int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )`
 <?php $haystack = 'how are you'; $needle = 'are'; if (strpos($haystack,$needle) !== false) { echo "$haystack contains $needle"; } ?>

주의:

검색하는 바늘이 건초 더미의 시작 부분에 있으면 위치 0을 반환합니다. 작동하지 않는 == === 를 수행해야 합니다.

A == 기호는 비교이며 왼쪽의 변수/식/상수가 오른쪽의 변수/식/상수와 같은 값인지 테스트합니다.

A === 기호는 두 변수/표현식/상수가 동일한지 AND 동일한 유형을 갖는지 확인하기 위한 비교입니다. 즉, 둘 다 문자열이거나 둘 다 정수입니다.


Community Wiki

strpos() .

 <?php $mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); // Note our use of ===. Simply, == would not work as expected // because the position of 'a' was the 0th (first) character. if ($pos === false) { echo "The string '$findme' was not found in the string '$mystring'."; } else { echo "The string '$findme' was found in the string '$mystring',"; echo " and exists at position $pos."; } ?>

Community Wiki

사용 strstr() 또는 stristr() 검색이 경우를 구분해야하는 경우 또 다른 옵션이 될 것입니다.


Community Wiki

SamGoody 및 Lego Stormtroopr 의견을 살펴보십시오.

여러 단어의 근접성/관련성을 기반으로 검색 결과의 순위 를 매기는 PHP 알고리즘을 찾고 있다면 여기에 PHP만으로 검색 결과를 생성하는 빠르고 쉬운 방법이 있습니다.

strpos() , preg_match() , strstr() 또는 stristr() 과 같은 다른 부울 검색 방법의 문제

  1. 여러 단어를 검색할 수 없습니다
  2. 결과는 순위가 없습니다

벡터 공간 모델tf-idf(항 빈도-역 문서 빈도)를 기반으로 하는 PHP 방법:

어려워 보이지만 의외로 쉽습니다.

문자열에서 여러 단어를 검색하려는 경우 핵심 문제는 각 단어에 가중치를 할당하는 방법입니다.

전체 문자열을 얼마나 대표하는지에 따라 문자열의 용어에 가중치를 줄 수 있다면 쿼리와 가장 잘 일치하는 항목으로 결과를 정렬할 수 있습니다.

이것은 SQL 전체 텍스트 검색이 작동하는 방식 과 그리 멀지 않은 벡터 공간 모델의 아이디어입니다.

 function get_corpus_index($corpus = array(), $separator=' ') { $dictionary = array(); $doc_count = array(); foreach($corpus as $doc_id => $doc) { $terms = explode($separator, $doc); $doc_count[$doc_id] = count($terms); // tf–idf, short for term frequency–inverse document frequency, // according to wikipedia is a numerical statistic that is intended to reflect // how important a word is to a document in a corpus foreach($terms as $term) { if(!isset($dictionary[$term])) { $dictionary[$term] = array('document_frequency' => 0, 'postings' => array()); } if(!isset($dictionary[$term]['postings'][$doc_id])) { $dictionary[$term]['document_frequency']++; $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0); } $dictionary[$term]['postings'][$doc_id]['term_frequency']++; } //from http://phpir.com/simple-search-the-vector-space-model/ } return array('doc_count' => $doc_count, 'dictionary' => $dictionary); } function get_similar_documents($query='', $corpus=array(), $separator=' '){ $similar_documents=array(); if($query!=''&&!empty($corpus)){ $words=explode($separator,$query); $corpus=get_corpus_index($corpus, $separator); $doc_count=count($corpus['doc_count']); foreach($words as $word) { if(isset($corpus['dictionary'][$word])){ $entry = $corpus['dictionary'][$word]; foreach($entry['postings'] as $doc_id => $posting) { //get term frequency–inverse document frequency $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2); if(isset($similar_documents[$doc_id])){ $similar_documents[$doc_id]+=$score; } else{ $similar_documents[$doc_id]=$score; } } } } // length normalise foreach($similar_documents as $doc_id => $score) { $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id]; } // sort from high to low arsort($similar_documents); } return $similar_documents; }

사례 1

 $query = 'are'; $corpus = array( 1 => 'How are you?', ); $match_results=get_similar_documents($query,$corpus); echo '<pre>'; print_r($match_results); echo '</pre>';

결과

 Array ( [1] => 0.52832083357372 )

사례 2

 $query = 'are'; $corpus = array( 1 => 'how are you today?', 2 => 'how do you do', 3 => 'here you are! how are you? Are we done yet?' ); $match_results=get_similar_documents($query,$corpus); echo '<pre>'; print_r($match_results); echo '</pre>';

결과

 Array ( [1] => 0.54248125036058 [3] => 0.21699250014423 )

사례 3

 $query = 'we are done'; $corpus = array( 1 => 'how are you today?', 2 => 'how do you do', 3 => 'here you are! how are you? Are we done yet?' ); $match_results=get_similar_documents($query,$corpus); echo '<pre>'; print_r($match_results); echo '</pre>';

결과

 Array ( [3] => 0.6813781191217 [1] => 0.54248125036058 )

가 만들어 질 개선을 많이하지만 모델이 같은 부울 연산자가없는 자연 쿼리에서 좋은 결과를 얻기의 방법 제공 strpos() , preg_match() , strstr() 또는 stristr() .

노타 베네

단어를 검색하기 전에 선택적으로 중복 제거

  • 따라서 인덱스 크기가 줄어들고 스토리지 요구 사항이 줄어듭니다.

  • 적은 디스크 I/O

  • 더 빠른 인덱싱 및 결과적으로 더 빠른 검색.

1. 정규화

  • 모든 텍스트를 소문자로 변환

2. 불용어 제거

  • 텍스트에서 실제 의미가 없는 단어를 제거합니다(예: 'and', 'or', 'the', 'for' 등).

3. 사전 대체

  • 동일하거나 유사한 의미를 가진 다른 단어로 대체하십시오. (예: '배고프다'와 '배고프다'를 '굶주림'으로 대체)

  • 단어를 본질적 의미로 더 줄이기 위해 추가 알고리즘 측정(눈덩이)을 수행할 수 있습니다.

  • 색상 이름을 해당하는 16진수로 대체

  • 정밀도를 줄여 숫자 값을 줄이는 것은 텍스트를 정규화하는 다른 방법입니다.

자원


Community Wiki

stripos() 사용하여 대소문자를 구분하지 않는 일치를 사용합니다.

 if (stripos($string,$stringToSearch) !== false) { echo 'true'; }

Community Wiki

"거짓" 및 "진실" 문제를 피하려면 substr_count를 사용할 수 있습니다.

 if (substr_count($a, 'are') > 0) { echo "at least one 'are' is present!"; }

strpos보다 약간 느리지만 비교 문제를 피할 수 있습니다.


Community Wiki

if (preg_match('/(are)/', $a)) { echo 'true'; }

Community Wiki

또 다른 옵션은 strstr() 함수를 사용하는 것입니다. 다음과 같은 것:

 if (strlen(strstr($haystack,$needle))>0) { // Needle Found }

참고 사항: strstr() 함수는 대소문자를 구분합니다. 대소문자를 구분하지 않는 검색의 경우 stristr() 함수를 사용하십시오.


Community Wiki

strpos , strstr 및 이와 유사한 기능 을 사용한 답변 중 아직 Multibyte String Functions (2015-05-08)에 대해 언급한 답변이 없다는 점에 약간 감동했습니다.

기본적으로 독일어, 프랑스어, 포르투갈어, 스페인어 등과 같은 일부 언어에 특정한 문자가 있는 단어를 찾는 데 문제 가 있는 경우 (예: ä , é , ô , ç , º , ñ ) mb_ 있는 함수. 따라서 허용되는 답변은 mb_strpos 또는 mb_stripos (대소문자 구분 없는 일치의 경우)를 사용합니다.

 if (mb_strpos($a,'are') !== false) { echo 'true'; }

모든 데이터가 UTF-8로 100% 라고 보장할 수 없는 경우 mb_ 함수를 사용할 수 있습니다.

Joel Spolsky 의 절대 최소값이 모든 소프트웨어 개발자가 유니코드 및 문자 집합에 대해 절대적으로, 긍정적으로 알아야 하는 이유를 이해하는 좋은 기사입니다.


Community Wiki

PHP에서 문자열에 특정 하위 문자열이 포함되어 있는지 확인하는 가장 좋은 방법은 다음과 같은 간단한 도우미 함수를 사용하는 것입니다.

 function contains($haystack, $needle, $caseSensitive = false) { return $caseSensitive ? (strpos($haystack, $needle) === FALSE ? FALSE : TRUE): (stripos($haystack, $needle) === FALSE ? FALSE : TRUE); }

설명:

  • strpos 는 문자열에서 대소문자를 구분하는 하위 문자열이 처음 나타나는 위치를 찾습니다.
  • stripos 는 문자열에서 대소문자를 구분하지 않는 하위 문자열이 처음 나타나는 위치를 찾습니다.
  • myFunction($haystack, $needle) === FALSE ? FALSE : TRUEmyFunction 항상 부울을 반환하도록 하고 하위 문자열의 인덱스가 0일 때 예기치 않은 동작을 수정합니다.
  • $caseSensitive ? A : B $caseSensitive 의 값에 따라 작업을 수행할 strpos 또는 stripos 를 선택합니다.

산출:

 var_dump(contains('bare','are')); // Outputs: bool(true) var_dump(contains('stare', 'are')); // Outputs: bool(true) var_dump(contains('stare', 'Are')); // Outputs: bool(true) var_dump(contains('stare', 'Are', true)); // Outputs: bool(false) var_dump(contains('hair', 'are')); // Outputs: bool(false) var_dump(contains('aren\'t', 'are')); // Outputs: bool(true) var_dump(contains('Aren\'t', 'are')); // Outputs: bool(true) var_dump(contains('Aren\'t', 'are', true)); // Outputs: bool(false) var_dump(contains('aren\'t', 'Are')); // Outputs: bool(true) var_dump(contains('aren\'t', 'Are', true)); // Outputs: bool(false) var_dump(contains('broad', 'are')); // Outputs: bool(false) var_dump(contains('border', 'are')); // Outputs: bool(false)

Community Wiki

strstr 함수를 사용할 수 있습니다.

 $haystack = "I know programming"; $needle = "know"; $flag = strstr($haystack, $needle); if ($flag){ echo "true"; }

내장 함수를 사용하지 않고:

 $haystack = "hello world"; $needle = "llo"; $i = $j = 0; while (isset($needle[$i])) { while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) { $j++; $i = 0; } if (!isset($haystack[$j])) { break; } $i++; $j++; } if (!isset($needle[$i])) { echo "YES"; } else{ echo "NO "; }

Community Wiki

아래 기능도 작동하며 다른 기능에 종속되지 않습니다. 기본 PHP 문자열 조작만 사용합니다. 개인적으로 나는 이것을 권장하지 않지만 어떻게 작동하는지 볼 수 있습니다:

 <?php if (!function_exists('is_str_contain')) { function is_str_contain($string, $keyword) { if (empty($string) || empty($keyword)) return false; $keyword_first_char = $keyword[0]; $keyword_length = strlen($keyword); $string_length = strlen($string); // case 1 if ($string_length < $keyword_length) return false; // case 2 if ($string_length == $keyword_length) { if ($string == $keyword) return true; else return false; } // case 3 if ($keyword_length == 1) { for ($i = 0; $i < $string_length; $i++) { // Check if keyword's first char == string's first char if ($keyword_first_char == $string[$i]) { return true; } } } // case 4 if ($keyword_length > 1) { for ($i = 0; $i < $string_length; $i++) { /* the remaining part of the string is equal or greater than the keyword */ if (($string_length + 1 - $i) >= $keyword_length) { // Check if keyword's first char == string's first char if ($keyword_first_char == $string[$i]) { $match = 1; for ($j = 1; $j < $keyword_length; $j++) { if (($i + $j < $string_length) && $keyword[$j] == $string[$i + $j]) { $match++; } else { return false; } } if ($match == $keyword_length) { return true; } // end if first match found } // end if remaining part } else { return false; } // end for loop } // end case4 } return false; } }

시험:

 var_dump(is_str_contain("test", "t")); //true var_dump(is_str_contain("test", "")); //false var_dump(is_str_contain("test", "test")); //true var_dump(is_str_contain("test", "testa")); //flase var_dump(is_str_contain("a----z", "a")); //true var_dump(is_str_contain("a----z", "z")); //true var_dump(is_str_contain("mystringss", "strings")); //true

Community Wiki

substr_count 를 사용하는 많은 답변은 결과가 >0 인지 확인합니다. 그러나 if 문은 0 을 false 와 동일하게 간주하므로 해당 검사를 피하고 직접 작성할 수 있습니다.

 if (substr_count($a, 'are')) {

존재 하지 않는지 확인하려면 ! 운영자:

 if (!substr_count($a, 'are')) {

Community Wiki

나는 이것에 약간의 문제가 있었고 마침내 나는 내 자신의 솔루션을 만들기로 결정했습니다. 정규식 엔진을 사용하지 않고:

 function contains($text, $word) { $found = false; $spaceArray = explode(' ', $text); $nonBreakingSpaceArray = explode(chr(160), $text); if (in_array($word, $spaceArray) || in_array($word, $nonBreakingSpaceArray) ) { $found = true; } return $found; }

이전 솔루션이 다른 단어의 접두사로 사용되는 단어에 대한 답변이 아님을 알 수 있습니다. 귀하의 예를 사용하려면:

 $a = 'How are you?'; $b = "a skirt that flares from the waist"; $c = "are";

위의 샘플에서 $a$b $c 가 포함되어 $a $c 가 포함되어 있다고 함수가 알려주기를 원할 수 있습니다.


Community Wiki

사용하여 문자열에서 단어의 발생을 찾는 또 다른 옵션 않는 strstr ()) stristr은 ( 다음과 같다 :

 <?php $a = 'How are you?'; if (strstr($a,'are')) // Case sensitive echo 'true'; if (stristr($a,'are')) // Case insensitive echo 'true'; ?>

Community Wiki

다음 세 가지 방법으로 수행할 수 있습니다.

 $a = 'How are you?';

1- strist()

 if (strlen(stristr($a,"are"))>0) { echo "true"; // are Found }

2- strpos()

 if (strpos($a, "are") !== false) { echo "true"; // are Found }

3- preg_match()

 if( preg_match("are",$a) === 1) { echo "true"; // are Found }

Community Wiki

단축 버전

 $result = false!==strpos($a, 'are');

Community Wiki

'단어'를 찾으려면 실제로 다른 단어의 일부일 수 있는 일련의 문자가 발생하는 것보다 다음이 좋은 해결책이 될 것입니다.

 $string = 'How are you?'; $array = explode(" ", $string); if (in_array('are', $array) ) { echo 'Found the word'; }

Community Wiki

대소문자를 구분하지 않는 형식을 사용해야 하므로 입력한 값이 small 거나 caps 경우 중요하지 않습니다.

 <?php $grass = "This is pratik joshi"; $needle = "pratik"; if (stripos($grass,$needle) !== false) { /*If i EXCLUDE : !== false then if string is found at 0th location, still it will say STRING NOT FOUND as it will return '0' and it will goto else and will say NOT Found though it is found at 0th location.*/ echo 'Contains word'; }else{ echo "does NOT contain word"; } ?>

여기서 stripos는 대소문자(소형/대문자)를 고려 하지 않고 헤이스택에서 바늘을 찾습니다.

출력이 있는 PHPCode 샘플


Community Wiki

아마도 다음과 같이 사용할 수 있습니다.

 <?php findWord('Test all OK'); function findWord($text) { if (strstr($text, 'ok')) { echo 'Found a word'; } else { echo 'Did not find a word'; } } ?>

Community Wiki

한 문자열이 다른 문자열에 포함되어 있는지 확인하려는 경우에만 preg_match() 사용하지 마십시오. 대신 strpos() 또는 strstr() 사용하면 더 빨라집니다. ( http://in2.php.net/preg_match )

 if (strpos($text, 'string_name') !== false){ echo 'get the string'; }

Community Wiki

문자열에 여러 특정 단어가 포함되어 있는지 확인하려면 다음을 수행할 수 있습니다.

 $badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat"); $string = "a string with the word ivoire"; $matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches); if ($matchFound) { echo "a bad word has been found"; } else { echo "your string is okay"; }

이것은 예를 들어 이메일을 보낼 때 스팸을 피하는 데 유용합니다.


Community Wiki

strpos 함수는 잘 작동하지만 case-insensitive PHP stripos 함수를 사용할 수 있습니다.

예를 들어,

 $result = stripos("I love PHP, I love PHP too!", "php"); if ($result === false) { // Word does not exist } else { // Word exists }

문자열에서 대소문자를 구분하지 않는 부분 문자열이 처음 나타나는 위치를 찾습니다.

단어가 문자열에 존재하지 않으면 false를 반환하고 그렇지 않으면 단어의 위치를 반환합니다.


Community Wiki

strpos는 인덱스 값으로 0을 반환할 수 있으므로 동일/동일하지 않은 연산자를 사용해야 합니다. 삼항 연산자가 마음에 들면 다음을 사용하는 것을 고려하십시오.

 echo FALSE === strpos($a,'are') ? 'false': 'true';

Community Wiki

문자열에 특정 단어가 포함되어 있는지 확인하시겠습니까?

이것은 문자열이 단어로 해석되어야 함을 의미합니다(아래 참고 참조).

이를 수행하고 구분 기호를 지정하는 한 가지 방법은 preg_split ( doc )을 사용하는 것입니다.

 <?php function contains_word($str, $word) { // split string into words // separators are substrings of at least one non-word character $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY); // now the words can be examined each foreach ($arr as $value) { if ($value === $word) { return true; } } return false; } function test($str, $word) { if (contains_word($str, $word)) { echo "string '" . $str . "' contains word '" . $word . "'\n"; } else { echo "string '" . $str . "' does not contain word '" . $word . "'\n" ; } } $a = 'How are you?'; test($a, 'are'); test($a, 'ar'); test($a, 'hare'); ?>

런이 준다

 $ php -f test.php string 'How are you?' contains word 'are' string 'How are you?' does not contain word 'ar' string 'How are you?' does not contain word 'hare'

참고: 여기에서 모든 기호 시퀀스에 대한 단어를 의미하지는 않습니다.

단어의 실제 정의는 PCRE 정규식 엔진이라는 의미에서 단어가 단어가 아닌 문자로 구분되는 단어 문자로만 구성된 하위 문자열입니다.

"단어" 문자는 모든 문자, 숫자 또는 밑줄 문자, 즉 Perl "단어"의 일부가 될 수 있는 모든 문자입니다. 문자와 숫자의 정의는 PCRE의 문자 테이블에 의해 제어되며 로케일별 일치(..)가 발생하는 경우 다를 수 있습니다.


Community Wiki

사용하다:

 $text = 'This is a test'; echo substr_count($text, 'is'); // 2 // So if you want to check if is exists in the text just put // in a condition like this: if (substr_count($text, 'is') > 0) { echo "is exists"; }

Community Wiki

출처 : http:www.stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word

반응형