Nice programing

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

nicepro 2020. 11. 20. 09:38
반응형

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


문자열에 배열에 저장된 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;
}

입력 된 내용에 관계없이 항상 "일치 할 수 없음"이 반환됩니다.

이것이 일을하는 올바른 방법입니까?


이 시도.

$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 ()를 사용 하십시오 .


이 시도:

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

- 감사


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


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

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

$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)

더 빠른 방법은 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";
}

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

위의 표현은 아마도 개선 될 수 있습니다 (저는이 분야에 대해 특별히 잘 모릅니다)

다음은 데모입니다.


다음은 주어진 문자열의 배열에서 모든 값을 검색하는 미니 함수입니다. 내 사이트에서이 정보를 사용하여 방문자 IP가 특정 페이지의 허용 목록에 있는지 확인합니다.

function array_in_string($str, array $arr) {
    foreach($arr as $arr_value) { //start looping the array
        if (strpos($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

strpos 함수는 그다지 엄격하지 않습니다. 대소 문자를 구분하지 않거나 단어의 일부와 일치 할 수 있습니다. http://php.net/manual/ro/function.strpos.php 검색을 더 엄격하게하려면 다른 기능을 사용해야합니다 (예 : 엄격한 기능에 대한이 사람 답변 확인 https://stackoverflow.com / a / 25633879 / 4481831 )


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

전체 문자열을 배열 값으로 확인하고 있습니다. 따라서 출력은 항상 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";

in_array ( http://php.net/manual/en/function.in-array.php ) 함수를 올바르게 사용하고 있지 않습니다 .

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

The $needle has to have a value in the array, so you first need to extract the url from the string (with a regular expression for example). Something like this:

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

If you are trying to get exact word match (not having paths inside urls)

$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));

Output:

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

    $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';

I find this fast and simple without running loop.

$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!';
}

Little explanation!

  1. Create new variable with $newStr replacing value in array of original string.

  2. Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.

  3. if it is vice versa of 2, i.e, while doing string comparison, both original and new string was not matched, that means, something got replaced, hence value in array exists in string.


THANKS for this - just been able to use this answer to the original question to develop a simple to use 404 Error page checker, for use on Custom 404 Error Pages.

Here goes:

You need an Array of livePages in your site, via array/ DB etc, even a listing of your <dir> tree will do this with modifications:

Using the original IDEA, but using similar-text instead of strpos, - this give you the facility to search for LIKE names, so also allows for TYPOS, so you can avoid or find Sound-a-like and Look-a-like names...

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

Hope this helps someone, like this article has helped me create a very simple search/match on an 404ErrorDoc page.

The design of the page will enable the server to put forward likely URL matches to any called URLS via the browser...

It workss - and is sooo simple, perhaps there are better ways to do this, but this way works.

참고URL : https://stackoverflow.com/questions/19445798/check-if-string-contains-a-value-in-array

반응형