2660

検討:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

上記のコードがあるとすると、ステートメントを書く正しい方法は何if ($a contains 'are')ですか?

4

36 に答える 36

7691

PHP 8では、 str_containsを使用してこれを行うことができます。

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

RFC

PHP8より前

strpos()別の文字列内のある文字列の出現を見つけるために使用される関数を使用できます。

$a = 'How are you?';

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

!== falseの使用は意図的なものであることに注意してください(目的の結果を返すこと!= falseも、返すこともありません)。干し草の山の文字列で針の文字列が始まるオフセット、または針が見つからない場合はブール値を返します。0は有効なオフセットであり、0は「falsey」であるため、のような単純な構造を使用することはできません。=== truestrpos()false!strpos($a, 'are')

于 2010-12-06T13:15:58.250 に答える
722

strpos他のユーザーが述べているように、に比べて単語の照合に適しているため、正規表現を使用できます。のstrposチェックはare、fare、care、stareなどの文字列に対してもtrueを返します。これらの意図しない一致は、単語の境界を使用することにより、正規表現で簡単に回避できます。

の単純な一致は次のareようになります。

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}

パフォーマンスの面でstrposは、約3倍高速です。一度に100万回比較したところ、preg_match終了までに1.5秒、strpos0.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.
}

もう1つ覚えておくべきことは、\b英語以外の異なる言語では機能しないということです。

これと解決策の説明はここから取られます

\b単語の始まりまたは終わりを表します(単語の境界)。この正規表現は、アップルパイのリンゴとは一致しますが、パイナップル、アップルカート、またはベイクアップルのリンゴとは一致しません。

「カフェ」はいかがですか?正規表現で「カフェ」という単語を抽出するにはどうすればよいですか?実際、\ bcafe\bは機能しません。なんで?「cafe」には非ASCII文字が含まれているため:é。\ bは、समुद्र、감사、месяц、などのUnicodeでは単純に使用できません。

Unicode文字を抽出する場合は、単語の境界を表す文字を直接定義する必要があります。

答え:(?<=[\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";
    }
于 2010-12-06T13:15:36.437 に答える
287

このような状況で役立つ小さなユーティリティ関数を次に示します。

// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}
于 2011-08-18T18:54:47.043 に答える
166

文字列に別の文字列が含まれているかどうかを判断するには、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を返します==、あなたがうまくいかない比較をするならば、あなたはする必要があります===

==符号は比較であり、左側の変数/式/定数が右側の変数/式/定数と同じ値であるかどうかをテストします。

===符号は、2つの変数/式/定数が等しいかどうかを確認するための比較です。ANDつまり、両方が文字列であるか、両方が整数であるかを確認します。

于 2010-12-06T14:06:12.977 に答える
162

これらの回答のほとんどは、文字列に部分文字列が含まれているかどうかを示しますが、特定の単語を探している場合、それは通常、部分文字ではなく、必要なものではありません。

違いは何ですか?部分文字列は、他の単語内に表示できます。

  • 「エリア」の先頭にある「あり」
  • 「うさぎ」の最後にある「あれ」
  • 「運賃」の真ん中にある「ある」

これを軽減する1つの方法は、単語の境界\b)と組み合わせた正規表現を使用することです。

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

このメソッドには、上記と同じ誤検知はありませんが、独自のエッジケースがいくつかあります。単語の境界は、単語以外の文字()と一致します。これは、、、、、またはで\Wはないものになりa-zます。つまり、数字とアンダースコアは単語文字としてカウントされ、次のようなシナリオは失敗します。A-Z0-9_

  • 「あなたは何を考えていますか?」の「あり」
  • 「loludunnowutそれらのare4?」の「are」

これよりも正確なものが必要な場合は、英語の構文解析を開始する必要があります。これは、かなり大きなワームの可能性があります(とにかく、構文が適切に使用されていることを前提としていますが、常に指定されているとは限りません)。

于 2014-09-02T23:23:19.453 に答える
75

見てください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.";
    }
?>
于 2010-12-06T13:16:30.263 に答える
66

検索で大文字と小文字を区別しないようにするか、または使用するstrstr()かどうかは、別のオプションです。stristr()

于 2010-12-06T14:16:25.437 に答える
56

SamGoodyとLegoStormtrooprのコメントをご覧ください。

複数の単語の近接性/関連性に基づいて検索結果をランク付けする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()

NOTABENE

オプションで、単語を検索する前に冗長性を排除します

  • これにより、インデックスサイズが削減され、必要なストレージが少なくなります。

  • より少ないディスクI/O

  • より高速なインデックス作成とその結果としてのより高速な検索。

1.正規化

  • すべてのテキストを小文字に変換する

2.ストップワードの削除

  • 本当の意味を持たないテキストから単語を削除します(「and」、「or」、「the」、「for」など)。

3.辞書の置換

  • 単語を同一または類似の意味を持つ他の単語に置き換えます。(例:「hungrily」と「hungry」のインスタンスを「hunger」に置き換えます)

  • 単語を本質的な意味にさらに減らすために、さらなるアルゴリズム的手段(雪だるま式)が実行され得る。

  • 色名を16進数に相当するものに置き換える

  • 精度を下げることによる数値の削減は、テキストを正規化する他の方法です。

資力

于 2014-10-15T19:21:34.320 に答える
51

以下を使用して、大文字と小文字を区別しないマッチングを利用しstripos()ます。

if (stripos($string,$stringToSearch) !== false) {
    echo 'true';
}
于 2013-10-24T07:30:13.997 に答える
43

「falsey」および「truthy」の問題を回避したい場合は、substr_countを使用できます。

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

strposよりも少し遅いですが、比較の問題を回避できます。

于 2013-07-09T08:38:53.050 に答える
37
if (preg_match('/(are)/', $a)) {
   echo 'true';
}
于 2013-10-10T11:22:00.683 に答える
32

もう1つのオプションは、strstr()関数を使用することです。何かのようなもの:

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

注意点:strstr()関数では大文字と小文字が区別されます。大文字と小文字を区別しない検索には、stristr()関数を使用します。

于 2012-08-20T16:20:31.683 に答える
30

strposここで使用した回答がなく、strstr同様の関数がマルチバイト文字列関数についてまだ言及していないことに少し感銘を受けました(2015-05-08)。

基本的に、ドイツ語、フランス語、ポルトガル語、スペイン語など、一部の言語に固有の文字を含む単語を見つけるのに問題がある場合(例: äéôçºñ)、を含む関数mb_。したがって、受け入れられた回答では、代わりにmb_strposまたはmb_stripos(大文字と小文字を区別しないマッチングの場合)を使用します。

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

UTF-8ですべてのデータが100%であることを保証できない場合は、関数を使用することをお勧めしますmb_

なぜ絶対最小であるかを理解するための良い記事は、 Joel SpolskyによるUnicodeと文字セット(言い訳なし!)について絶対に、積極的に知っておく必要があります。

于 2015-05-08T16:18:40.503 に答える
30

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の値に応じて、strposまたはを選択して作業を行います。stripos$caseSensitive

出力:

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)
于 2016-02-21T18:39:50.807 に答える
27

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 ";
}
于 2015-08-27T16:59:57.427 に答える
25

以下の関数も機能し、他の関数に依存しません。ネイティブの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 
于 2013-09-19T14:00:43.570 に答える
24

substr_count結果がであるかどうかをチェックするを使用する多くの回答>0。ただし、ifステートメントはゼロをfalseと同じと見なすため、そのチェックを回避して直接書き込むことができます。

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

存在しないかどうかを確認するには、!演算子を追加します。

if (!substr_count($a, 'are')) {
于 2016-03-21T12:39:16.427 に答える
23

私はこれにいくつかの問題を抱えていました、そして最終的に私は自分自身の解決策を作成することを選びました。正規表現エンジンを使用しない場合:

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

于 2014-03-18T15:49:33.880 に答える
21

strstr( )およびstristr( )を使用して文字列から単語の出現を検索する別のオプションは、次のようになります。

<?php
    $a = 'How are you?';
    if (strstr($a,'are'))  // Case sensitive
        echo 'true';
    if (stristr($a,'are'))  // Case insensitive
        echo 'true';
?>
于 2014-03-13T05:48:28.420 に答える
19

これは、次の3つの方法で実行できます。

 $a = 'How are you?';

1- stristr()

 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
 }
于 2015-12-19T10:57:56.843 に答える
16

速記バージョン

$result = false!==strpos($a, 'are');
于 2015-03-13T08:29:26.180 に答える
15

preg_match()ある文字列が別の文字列に含まれているかどうかだけを確認したい場合は使用しないでください。strpos()代わりに、または代わりに使用strstr()してください。(http://in2.php.net/preg_match

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}
于 2014-04-05T11:17:01.713 に答える
15

実際には別の単語の一部である可能性のある一連の文字の出現ではなく、「単語」を見つけるには、次の方法が適切な解決策になります。

$string = 'How are you?';
$array = explode(" ", $string);

if (in_array('are', $array) ) {
    echo 'Found the word';
}
于 2015-04-17T06:31:25.093 に答える
14

大文字と小文字を区別しない形式を使用する必要があります。入力した値が含まれているかどうかは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は、大文字と小文字を区別せずにheystackで針を見つけます(スモール/キャップ)。

出力付きのPHPCodeサンプル

于 2015-03-03T19:02:22.273 に答える
14

多分あなたはこのようなものを使うことができます:

<?php
    findWord('Test all OK');

    function findWord($text) {
        if (strstr($text, 'ok')) {
            echo 'Found a word';
        }
        else
        {
            echo 'Did not find a word';
        }
    }
?>
于 2015-04-07T12:51:26.843 に答える
13

文字列に複数の特定の単語が含まれているかどうかを確認する場合は、次の操作を実行できます。

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

これは、たとえば電子メールを送信するときにスパムを回避するのに役立ちます。

于 2015-10-14T14:40:45.677 に答える
12

strpos関数は正常に機能しますcase-insensitiveが、段落内の単語をチェックする場合は、のstripos関数を使用できますPHP

例えば、

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

文字列内で大文字と小文字を区別しない部分文字列が最初に出現する位置を見つけます。

単語が文字列に存在しない場合はfalseを返し、そうでない場合は単語の位置を返します。

于 2015-05-31T05:52:08.577 に答える
12

文字列は以下の関数で確認できます。

function either_String_existor_not($str, $character) {
    return strpos($str, $character) !== false;
}
于 2015-11-03T07:34:55.880 に答える
10

strposはインデックス値として0を返す可能性があるため、同一/非同一の演算子を使用する必要があります。三項演算子が好きな場合は、次の使用を検討してください(少し逆になっているようです)。

echo FALSE === strpos($a,'are') ? 'false': 'true';
于 2014-10-15T19:47:40.940 に答える
9

文字列に特定の単語が含まれているかどうかを確認しますか?

これは、文字列を単語に解決する必要があることを意味します(以下の注を参照)。

これを行い、区切り文字を指定する1つの方法は、preg_splitdoc)を使用することです。

<?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の文字テーブルによって制御され、ロケール固有のマッチングが行われている場合は異なる場合があります(..)

于 2015-09-23T22:16:50.383 に答える
9

使用する:

$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";
}
于 2016-01-16T09:43:50.853 に答える
8

特定の文字列の別の解決策:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;
}

関数を使用することもできstrpos()ます。

于 2015-12-17T07:49:19.293 に答える
8

マルチバイト文字列との組み込み関数と拡張機能を使用することもできstrchr()ます。これらの関数は文字列の一部を返し、何も見つからない場合は返します。strrchr()mb_strchr()mb_strrchr()FALSE

  • strchr()-文字列の最初の出現を検索します(のエイリアスですstrstr())。
  • strrchr()-文字列内の最後の文字を検索します。
于 2016-11-05T12:24:46.240 に答える
7

私は良い考えは使用することだと思いますmb_stpos

$haystack = 'How are you?';
$needle = 'are';

if (mb_strpos($haystack, $needle) !== false) {

    echo 'true';
}

このソリューションでは大文字と小文字が区別され、すべてのUnicode文字に対して安全であるためです。


しかし、あなたはこのようにすることもできます(sauchの応答はまだありませんでした):

if (count(explode($needle, $haystack)) > 1) {

    echo 'true';
}

このソリューションでは、大文字と小文字が区別され、Unicode文字に対して安全です

さらに、式で否定を使用しないため、コードの可読性が向上します


関数を使用した他の解決策は次のとおりです。

function isContainsStr($haystack, $needle) {

    return count(explode($needle, $haystack)) > 1;
}

if (isContainsStr($haystack, $needle)) {

    echo 'true';
}
于 2017-02-07T13:57:59.913 に答える
6

使用する:

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

マルチバイトの安全なstrpos()操作を実行します。

于 2016-04-07T15:15:40.947 に答える
6

より簡単なオプション:

return ( ! empty($a) && strpos($a, 'are'))? true : false;
于 2016-11-02T05:35:00.453 に答える