文字列に配列の値が含まれているかどうかを確認します


82

文字列に配列に格納されているURLが少なくとも1つ含まれているかどうかを検出しようとしています。

これが私の配列です:

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

文字列はユーザ​​ーが入力し、PHP経由で送信します。確認ページで、入力したURLが配列に含まれているかどうかを確認したいと思います。

私は以下を試しました:

$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
    echo "Match found"; 
    return true;
}
else
{
    echo "Match not found";
    return false;
}

何を入力しても、戻り値は常に「一致が見つかりません」です。

これは物事を行う正しい方法ですか?


私の答えをチェックしてください、あなたはそれが役に立つと思うでしょう。
FarrisFahad

回答:


88

これを試して。

$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
    //if (strstr($string, $url)) { // mine version
    if (strpos($string, $url) !== FALSE) { // Yoshi version
        echo "Match found"; 
        return true;
    }
}
echo "Not found!";
return false;

大文字と小文字を区別しないチェックを行う場合は、stristr()またはstripos()を使用してください。


3
ほとんど-これは「一致が見つかりません」をエコーし​​、リストの最初のURLが一致しない場合、別のURLが一致する場合でも、falseを返します。elseブロックのコンテンツはforeachループの下に移動する必要があります。
Ulrich Schmidt-Goertz 2013年

これを見つけてくれてありがとう。ちょうど私の答えを改善しました。
Daniele Vrut 2013年

$ stringの後の「)」も見逃しました:)
danyo 2013年

7
マニュアルから:**Note**: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
ヨッシー

5
@danyoユーザーがのようなドメインを入力した場合、これは機能しませんsite3.com。一致mysite3.comしてはならないときに一致します
billyonecan 2013年

22

これを試して:

$owned_urls= array('website1.com', 'website2.com', 'website3.com');

$string = 'my domain name is website3.com';

$url_string = end(explode(' ', $string));

if (in_array($url_string,$owned_urls)){
    echo "Match found"; 
    return true;
} else {
    echo "Match not found";
    return false;
}

-ありがとう


8
これは、文字列がスペースで区切られていることを前提としています。それは次の文字列では動作しません例えばMy url is https://website3.com
ЕлинЙ.

4
そして、「私はwebsite3.comドメインを持っています」では機能しません。これは、文字列は最後であると仮定しますが、ユーザが確定されたテキストを扱うことができないときに
サミュエル・フィッセル

20

str_replacecountパラメータを使用した単純なものはここで機能します:

$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
  echo "One of Array value is present in the string.";
}

詳細-https ://www.techpurohit.com/extended-behaviour-explode-and-strreplace-php


ニース、私は1つの疑問があります..これは文字列のURLを一致させるためにうまく機能します...私は文字列を持っています$ string = 'you-are-nice'; $ string2 = 'you-are-nicer'; そして私の$ match = 'nice'; 一致文字列が適切であっても、適切ではなく、適切な単語に一致する必要があります...
Srinivas08 2017年

15

配列内の文字列を見つけるだけの場合、これははるかに簡単でした。

$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}

1
入力配列は実際には文字列です。
ブルギ2017

3
私はこれがあると思いBEST ANSWERが、理由コードでの単純なミスのupvotesを受信しませんでした。@Burgi答えを編集しましたが、今では配列であり、さらに複数のサブ配列であり、彼の方法はまだ非常にうまく機能しています!!
タリック2018年

これはうまく機能しますが、配列がどのキーと一致したかはわかりません。
ahinkle

8
$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');

$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0; 
var_dump($result );

出力

bool(true)

2
参考のため; create_functionPHP 7.2では非推奨です
Darryl E. Clarke

6

より速い方法はpreg_matchを使用することだと思います。

$user_input = 'Something website2.com or other';
$owned_urls_array = array('website1.com', 'website2.com', 'website3.com');

if ( preg_match('('.implode('|',$owned_urls_array).')', $user_input)){
    echo "Match found"; 
}else{
    echo "Match not found";
}

4
このコードスニペットをありがとうございます。これは、限られた即時のヘルプを提供する可能性があります。適切な説明が大幅にこれは問題に良い解決策であり、他、同様の質問を将来の読者にそれがより便利になるだろう、なぜ示すことによって、その長期的な価値を向上させるであろう。あなたが行った仮定を含むいくつかの説明を追加するためにあなたの答えを編集してください。ref
Alpert。ターカー2018年

私はそれがより良い答えだと思います
dryobs 2018年

より安全にするには、ドットをパターンでエスケープする必要があります:addcslashes(implode('|', $owned_urls_array, '.'))
dryobs 2018年

コードは少ないですが、strposよりも間違いなくはるかに遅い
hndcrftd

4

これは、指定された文字列の配列からすべての値を検索するミニ関数です。私は自分のサイトでこれを使用して、訪問者のIPが特定のページの許可リストにあるかどうかを確認します。

function array_in_string($str, array $arr) {
    foreach($arr as $arr_value) { //start looping the array
        if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
    }
    return false; //else return false
}

使い方

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
    echo "first: Match found<br>"; 
}
else {
    echo "first: Match not found<br>";
}

//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
    echo "second: Match found<br>"; 
}
else {
    echo "second: Match not found<br>";
}

デモ:http//phpfiddle.org/lite/code/qf7j-8m09


1
大文字と小文字を区別しないバージョンの使用では、大文字と小文字が区別されますstripos
hndcrftd

3

$string常に一貫している場合(つまり、ドメイン名が常に文字列の最後にある場合)、で使用explode()してend()から、を使用in_array()して一致を確認できます(@Anand Solankiが回答で指摘しているように)。

そうでない場合は、正規表現を使用して文字列からドメインを抽出し、を使用in_array()して一致を確認することをお勧めします。

$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);

if (empty($matches[1])) {
  // no domain name was found in $string
} else {
  if (in_array($matches[1], $owned_urls)) {
    // exact match found
  } else {
    // exact match not found
  }
}

上記の表現はおそらく改善される可能性があります(私はこの分野に特に精通していません)

これがデモです


2

内破と|の区切り文字を使用して配列値を連結できます。次に、preg_matchを使用して値を検索します。

これが私が思いついた解決策です...

$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}

エレガントであるためのチェックされた答えでなければなりません
ceyquem

1
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

1

文字列全体を配列値にチェックしています。したがって、出力は常にfalseです。

私は両方を使用array_filterstrpos、この場合は。

<?php
$urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$check = array_filter($urls, function($url){
    global $string;
    if(strpos($string, $url))
        return true;
});
echo $check?"found":"not found";

0

関数in_array(http://php.net/manual/en/function.in-array.php)を正しく使用していません:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

$ needleは配列に値を持っている必要があるため、最初に文字列からURLを抽出する必要があります(たとえば、正規表現を使用)。このようなもの:

$url = extrctUrl('my domain name is website3.com');
//$url will be 'website3.com'
in_array($url, $owned_urls)

0

完全に一致する単語を取得しようとしている場合(URL内にパスがない)

$string = 'my domain name is website3.com';
$words = explode(' ', $string); 
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
var_dump(array_intersect($words, $owned_urls));

出力:

array(1) { [4]=> string(12) "website3.com" }

0
    $message = "This is test message that contain filter world test3";

    $filterWords = array('test1', 'test2', 'test3');

    $messageAfterFilter =  str_replace($filterWords, '',$message);

    if( strlen($messageAfterFilter) != strlen($message) )
        echo 'message is filtered';
    else
        echo 'not filtered';

0

ループを実行しなくても、これは高速でシンプルです。

$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";

$newStr = str_replace($array, "", $string);

if(strcmp($string, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

$newStr = str_replace($array, "", $string2);

if(strcmp($string2, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

少し説明!

  1. $newStr元の文字列の配列の値を置き換えて、新しい変数を作成します。

  2. 文字列の比較を行う-値が0の場合、つまり、文字列は等しく、何も置き換えられていないため、配列の値は文字列に存在しません。

  3. 2の逆の場合、つまり文字列の比較中に、元の文字列と新しい文字列の両方が一致しなかった場合、つまり、何かが置き換えられたため、配列の値が文字列に存在します。


0
  $search = "web"
    $owned_urls = array('website1.com', 'website2.com', 'website3.com');
          foreach ($owned_urls as $key => $value) {
         if (stristr($value, $search) == '') {
        //not fount
        }else{
      //found
       }

これは、大文字と小文字を区別せず、高速な部分文字列を検索するための最良のアプローチです。

immysqlのように

例:

name = "%web%"であるテーブルから*を選択します


0

私は私のために働くこの機能を思いついた、これが誰かを助けることを願っています

$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';

function checkStringAgainstList($str, $word_list)
{
  $word_list = explode(', ', $word_list);
  $str = explode(' ', $str);

  foreach ($str as $word):
    if (in_array(strtolower($word), $word_list)) {
        return TRUE;
    }
  endforeach;

  return false;
}

また、一致する単語が他の単語の一部である場合、strpos()を使用した回答はtrueを返すことに注意してください。たとえば、単語リストに「st」が含まれ、文字列に「street」が含まれている場合、strpos()はtrueを返します。


-3

これに感謝します-元の質問に対するこの回答を使用して、カスタム404エラーページで使用するための使いやすい404エラーページチェッカーを開発することができました。

ここに行きます:

配列/ DBなどを介してサイトにlivePagesの配列が必要です。<dir>ツリーのリストでさえ、変更を加えてこれを行います。

元のIDEAを使用しますが、strposの代わりに類似テキストを使用します-これにより、LIKE名を検索する機能が提供されるため、TYPOSも可能になるため、Sound-a-likeおよびLook-a-like名を回避または検索できます....。

<?php
// We need to GRAB the URL called via the browser ::
$requiredPage = str_replace ('/', '',$_SERVER[REQUEST_URI]);

// We need to KNOW what pages are LIVE within the website ::
$livePages = array_keys ($PageTEXT_2col );

foreach ($livePages as $url) {

if (similar_text($requiredPage,  $url, $percent)) {
    $percent = round($percent,2); // need to avoid to many decimal places ::
    //   if (strpos($string, $url) !== FALSE) { // Yoshi version
    if (round($percent,0) >= 60) { // set your percentage of "LIKENESS" higher the refiner the search in your array ::
        echo "Best Match found = " . $requiredPage . " > ,<a href='http://" . $_SERVER['SERVER_NAME'] . "/" . $url . "'>" . $url . "</a> > " . $percent . "%"; 
        return true;
    } 
}
}    
echo "Sorry Not found = " . $requiredPage; 
return false;
?>

この記事のように、これが誰かに役立つことを願っています。404ErrorDocページで非常に単純な検索/一致を作成するのに役立ちました。

ページのデザインにより、サーバーはブラウザを介して呼び出されたURLに一致する可能性のあるURLを提示できるようになります...

それは機能します-そしてとても簡単です、おそらくこれを行うためのより良い方法がありますが、この方法は機能します。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.