문자열에 배열의 값이 포함되어 있는지 확인


82

문자열에 배열에 저장된 URL이 하나 이상 포함되어 있는지 감지하려고합니다.

다음은 내 배열입니다.

$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

답변:


89

이 시도.

$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
거의-이것은 "Match not found"를 표시하고 다른 URL이 있더라도 목록의 첫 번째 URL이 일치하지 않으면 false를 반환합니다. else블록의 내용은 foreach루프 아래로 이동해야합니다 .
Ulrich Schmidt-Goertz

이것을 발견해 주셔서 감사합니다. 내 대답을 개선했습니다.
다니엘 Vrut

또한 : $ 문자열 후 ")"밖으로 놓친
danyo

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.
Yoshi

5
@danyo 사용자가 같은 도메인을 입력하면 작동하지 않습니다 site3.com. 그것은 일치 mysite3.com할 때 그것은 안
billyonecan

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
'웹 사이트 3.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


Nice, 한 가지 의심이 있습니다 .. 이것은 문자열의 URL과 일치하는 데 잘 작동합니다 ... 문자열이 있습니다 $ string = 'you-are-nice'; $ string2 = '당신은 더 낫다'; 그리고 내 $ match = 'nice'; 내 일치하는 문자열이 ... 좋은하지 더 좋은 경우에도 단어 좋은 일치 할 필요
Srinivas08

15

원하는 것은 배열에서 문자열을 찾는 것이라면 훨씬 쉬웠습니다.

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

1
입력 배열은 실제로 문자열입니다.
Burgi

3
나는 이것이 최선의 대답 이라고 생각 하지만 코드의 간단한 실수로 인해 upvotes를받지 못했습니다. @Burgi 나는 대답을 편집했으며 이제는 배열이며 더 많은 하위 배열이며 그의 방법은 여전히 ​​잘 작동합니다!
타릭

이것은 잘 작동하지만 배열이 일치하는 키를 알려주지 않습니다.
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
Alper t. Turker

나는 그것이 더 나은 답변을 생각
dryobs

보안을 강화하려면 점을 패턴으로 이스케이프해야합니다.addcslashes(implode('|', $owned_urls_array, '.'))
dryobs

코드는 적지 만 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()with 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

implode 및 구분 기호로 배열 값을 연결할 수 있습니다. | 그런 다음 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_filter와 둘 다 사용합니다 strpos.

<?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
       }

이것은 대소 문자를 구분하지 않고 빠른 하위 문자열에 대한 최상의 접근 방식 검색입니다.

메신저 mysql처럼

전의:

이름 = "% 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도 허용되므로 유사 사운드 및 유사 이름을 피하거나 찾을 수 있습니다. ...

<?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.