Program Tip

PHP-문자열에 특정 텍스트가 포함되어 있는지 확인하는 방법

programtip 2020. 11. 3. 18:52
반응형

PHP-문자열에 특정 텍스트가 포함되어 있는지 확인하는 방법


이 질문에 이미 답변이 있습니다.

<?php
$a = '';

if($a exist 'some text')
    echo 'text';
?>

위의 코드가 있다고 가정합니다. "if ($ a exist 'some text')"문을 작성하는 방법은 무엇입니까?


strpos함수 사용 : http://php.net/manual/en/function.strpos.php

$haystack = "foo bar baz";
$needle   = "bar";

if( strpos( $haystack, $needle ) !== false) {
    echo "\"bar\" exists in the haystack variable";
}

귀하의 경우 :

if( strpos( $a, 'some text' ) !== false ) echo 'text';

참고 내 사용하는 !==연산자 (대신 != false하거나 == true또는 단지 if( strpos( ... ) ) {) 때문이다 "truthy"/ "falsy" 의 반환 값의 PHP의 처리의 성격 strpos.


빈 문자열은 거짓이므로 다음과 같이 작성할 수 있습니다.

if ($a) {
    echo 'text';
}

해당 문자열에 특정 하위 문자열이 있는지 묻는 경우에도 다음을 사용할 수 있습니다 strpos().

if (strpos($a, 'some text') !== false) {
    echo 'text';
}

http://php.net/manual/en/function.strpos.php 문자열에 '일부 텍스트'가 있으면 더 멋지다고 생각합니까?

if(strpos( $a , 'some text' ) !== false)

strpos()또는 stripos()사용 하여 문자열에 주어진 바늘이 있는지 확인할 수 있습니다 . 발견 된 위치를 반환하고 그렇지 않으면 FALSE를 반환합니다.

연산자 ===또는`! ==를 사용하여 PHP에서 FALSE를 0과 다릅니다.


== 비교 연산자사용하여 변수가 텍스트와 같은지 확인할 수 있습니다 .

if( $a == 'some text') {
    ...

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";
}

문서보기


문자열에 단어가 존재하는지 알고 싶다면 이것을 사용할 수 있습니다. 변수가 문자열인지 아닌지 알고 싶다면 질문에서 명확하지 않습니다. 여기서 'word'는 문자열에서 검색하는 단어입니다.

if (strpos($a,'word') !== false) {
echo 'true';
}

or use the is_string method. Whichs returns true or false on the given variable.

<?php
$a = '';
is_string($a);
?>

you can use this code

$a = '';

if(!empty($a))
  echo 'text';

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

참고URL : https://stackoverflow.com/questions/15305278/php-how-to-check-if-a-string-contains-a-specific-text

반응형