Consider:고려사항:
$a = 'How are you?'; if ($a contains 'are') echo 'true';
Suppose I have the code above, what is the correct way to write the statement 위의 코드가 있다고 가정하면, 스테이트먼트를 작성하는 올바른 방법은 무엇입니까?if ($a contains 'are')
??
질문에 대한 답변
Now with PHP 8 you can do this using str_contains:PHP 8에서는 str_contains를 사용하여 이 작업을 수행할 수 있습니다.
if (str_contains('How are you', 'are')) { echo 'true'; }
Before PHP 8PHP 8 이전
You can use the strpos()
function which is used to find the occurrence of one string inside another one:다음 함수를 사용하여 어떤 문자열이 다른 문자열 내에서 발생하는지 확인할 수 있습니다.
$a = 'How are you?'; if (strpos($a, 'are') !== false) { echo 'true'; }
Note that the use of 주의:!== false
is deliberate (neither 의도적(의도적)!= false
nor 도 아니다=== true
will return the desired result); 원하는 결과를 반환한다).strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean 니들 문자열이 건초 스택 문자열로 시작되는 오프셋 또는 부울 중 하나를 반환합니다.false
if the needle isn’t found.바늘이 발견되지 않으면요 Since 0 is a valid offset and 0 is “falsey”, we can’t use simpler constructs like 0은 유효한 오프셋이고 0은 “false”이기 때문에 다음과 같은 간단한 구문을 사용할 수 없습니다.!strpos($a, 'are')
..
You could use regular expressions as it’s better for word matching compared to 단어 매칭이 더 좋기 때문에 정규 표현을 사용할 수 있습니다.strpos
, as mentioned by other users.(다른 유저에 의해서 기재되어 있습니다. A astrpos
check for 을 조사하다.are
will also return true for strings such as: fare, care, stare, etc.또한 요금, 관리, 응시 등의 문자열에 대해서도 true가 반환됩니다. These unintended matches can simply be avoided in regular expression by using word boundaries.이러한 의도하지 않은 일치는 단어 경계를 사용함으로써 정규 표현에서 간단히 피할 수 있습니다.
A simple match for 의 간단한 매칭are
could look something like this:다음과 같이 될 수 있습니다.
$a = 'How are you?'; if (preg_match('/bareb/', $a)) { echo 'true'; }
On the performance side, 퍼포먼스 측면에서는strpos
is about three times faster.약 3배 빠릅니다. When I did one million compares at once, it took preg_match
1.5 seconds to finish and for 한 번에 100만번 비교해보니까 1.5초 걸려서strpos
it took 0.5 seconds.0.5초 걸렸어요
Edit: In order to search any part of the string, not just word by word, I would recommend using a regular expression like편집: 단어별이 아니라 문자열의 모든 부분을 검색하려면 다음과 같은 정규 표현을 사용하는 것이 좋습니다.
$a = 'How are you?'; $search = 'are y'; if(preg_match("/{$search}/i", $a)) { echo 'true'; }
The 그i
at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.정규 표현 끝에 있는 정규 표현은 대소문자를 구분하지 않도록 변경됩니다.필요하지 않은 경우 생략할 수 있습니다.
Now, this can be quite problematic in some cases as the $search string isn’t sanitized in any way, I mean, it might not pass the check in some cases as if $search 문자열이 어떤 식으로든 삭제되지 않기 때문에 이것은 매우 문제가 될 수 있습니다. 즉, 어떤 경우에는 다음과 같이 검사를 통과하지 못할 수 있습니다.$search
is a user input they can add some string that might behave like some different regular expression…사용자 입력입니다.다른 정규 표현처럼 동작할 수 있는 문자열을 추가할 수 있습니다.
Also, here’s a great tool for testing and seeing explanations of various regular expressions Regex101또한 다양한 정규 표현 Regex101을 테스트하고 설명을 보기 위한 훌륭한 도구입니다.
To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:두 기능 세트를 하나의 다목적 기능(대문자와 소문자를 구분하여 포함)으로 결합하려면 다음과 같이 사용할 수 있습니다.
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. }
One more thing to take in mind, is that 한 가지 더 명심해야 할 것은b
will not work in different languages other than english.영어 이외의 다른 언어에서는 동작하지 않습니다.
The explanation for this and the solution is taken from here:이것과 솔루션에 대한 설명은 여기서 인용합니다.
b
represents the beginning or end of a word (Word Boundary).는 단어의 시작 또는 끝을 나타냅니다(단어 경계). This regex would match apple in an apple pie, but wouldn’t match apple in pineapple, applecarts or bakeapples.이 정규식은 애플 파이에는 사과와 매치되지만 파인애플, 애플카트, 베이크애플에는 매치되지 않습니다.How about “café”?카페는 어때? How can we extract the word “café” in regex?‘카페’라는 단어를 정규식으로 추출하려면 어떻게 해야 하죠? Actually, bcaféb wouldn’t work. Why?사실, bcafé는 작동하지 않아요. 왜요? Because “café” contains non-ASC카페에는 ASC 이외의 것이 포함되어 있기 때문에II character: é. b can’t be simply used with Unicode such as समुद्र, 감사, месяц and 😉 .II 문자: é. b는 단순히 유니코드, as, ., 😉와 같이 사용할 수 없습니다.
When you want to extract Unicode characters, you should directly define characters which represent word boundaries.유니코드 문자를 추출하려면 단어 경계를 나타내는 문자를 직접 정의해야 합니다.
The answer: 답은 다음과 같습니다.
(?<=[s,.:;"'] ^)UNICODE_WORD(?=[s,.:;"'] $)
So in order to use the answer in PHP, you can use this function:따라서 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; }
And if you want to search for array of words, you can use this:단어 배열을 검색하려면 다음을 사용할 수 있습니다.
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; }
As of PHP 8.0.0 you can now use str_containsPHP 8.0.0 이후 str_contains를 사용할 수 있게 되었습니다.
<?php if (str_contains('abc', '')) { echo "Checking the existence of the empty string will always return true"; }
Here is a little utility function that is useful in situations like this여기 이런 경우에 유용한 작은 유틸리티 기능이 있습니다.
// returns true if $needle is a substring of $haystack function contains($needle, $haystack) { return strpos($haystack, $needle) !== false; }
To determine whether a string contains another string you can use the PHP function strpos()
.문자열에 다른 문자열이 포함되어 있는지 여부를 확인하려면 PHP 함수를 사용합니다.
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"; } ?>
CAUTION:주의:
If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a 찾고 있는 바늘이 건초 더미의 시작점에 있으면 위치 0을 반환합니다.==
compare that will not work, you will need to do a 비교는 기능하지 않습니다만,===
A ==
sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.부호는 비교이며 왼쪽에 있는 변수/식/상수가 오른쪽에 있는 변수/식/상수와 동일한 값을 가지는지 여부를 테스트합니다.
A ===
sign is a comparison to see whether two variables / expresions / constants are equal 부호는 두 변수/표현/상수가 동일한지 여부를 확인하는 비교입니다.AND
have the same type – i.e. both are strings or both are integers.유형이 같습니다. 즉, 둘 다 문자열이거나 둘 다 정수입니다.
While most of these answers will tell you if a substring appears in your string, that’s usually not what you want if you’re looking for a particular word, and not a substring.이러한 답변의 대부분은 문자열에 하위 문자열이 표시되는지 여부를 알려 주지만, 하위 문자열이 아닌 특정 단어를 찾는 경우에는 일반적으로 원하는 단어가 아닙니다.
What’s the difference?뭐가 다른데? Substrings can appear within other words:하위 문자열은 다음 단어로 표시될 수 있습니다.
- The “are” at the beginning of “area”“area”의 선두에 있는 “are”
- The “are” at the end of “hare”“hare”의 끝에 있는 “are”는
- The “are” in the middle of “fares”‘운임’의 한복판에 있는 ‘현상’
One way to mitigate this would be to use a regular expression coupled with word boundaries (이를 완화하기 위한 한 가지 방법은 정규 표현을 단어 경계와 조합하여 사용하는 것입니다.b
):):
function containsWord($str, $word) { return !!preg_match('#\b' . preg_quote($word, '#') . '\b#i', $str); }
This method doesn’t have the same false positives noted above, but it does have some edge cases of its own.이 메서드는 위에서 설명한 것과 동일한 false positive를 가지고 있지 않지만 자체 엣지 케이스가 있습니다. Word boundaries match on non-word characters (단어 경계는 단어가 아닌 문자와 일치합니다(W
), which are going to be anything that isn’t ( )이러한 것은, 다른 것이 됩니다.a-z
, ,A-Z
, ,0-9
, or , 또는_
. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:즉, 숫자와 밑줄이 워드 문자로 카운트되고 다음과 같은 시나리오가 실패합니다.
- The “are” in “What _are_ you thinking?”“무슨 생각을 하고 있니?”의 “지금”은?
- The “are” in “lol u dunno wut those are4?”“lol u donno wut thats 4?”의 “are”는?
If you want anything more accurate than this, you’ll have to start doing English language syntax parsing, and that’s a pretty big can of worms (and assumes proper use of syntax, anyway, which isn’t always a given).이것보다 더 정확한 것을 원한다면 영어 구문 해석을 시작해야 합니다.그것은 상당히 많은 웜입니다(어쨌든 구문을 적절하게 사용하는 것은 항상 정해진 것은 아닙니다).