简体   繁体   中英

PHP compare two arrays and filter array has specific values

There are two arrays.

files array holds file names.

contents array holds html texts.

I want to check filter files which are not included in contents.

$files = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
$contents = ["<p>random text</p>", "<p>another random text</p>", "<img src='1.jpg'>"];

I tried like below but did not work well.

$filter = []; 
foreach ($contents as $key => $content) {

    foreach($files as $key => $file) {

        if(strpos($content, $file) == false) {
            $filter[$key] = $file;
        }               
    }
}

Thank you very much.

Look my code:

$files = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
$contents = ["<p>random text</p>", "<p>another random text</p>", "<img src='1.jpg'>"];

$included = [];
foreach ($contents as $content) {
    foreach ($files as $file) {
        if (strpos(strtolower($content), strtolower($file))) {
            $included[] = $file;
        }
    }
}

print_r(array_diff($files, $included));
Array ( [1] => 2.jpg [2] => 3.jpg [3] => 4.jpg [4] => 5.jpg )

You can try this :

foreach ($contents as $content) {

    foreach($files as $file) {

        if(!strpos($content, $file)) {
            if (!in_array($file, $filter)) {
                $filter[] = $file;
            }
        } else {
            if (($key = array_search($file, $filter)) !== false) {
                unset($filter[$key]);
            }
        }
    }
}

Try this:

$files = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
$contents = ["<p>random text</p>", "<p>another random text</p>", "<img     src='1.jpg'>"];
$alltxt="";

foreach($contents as $txt)$alltxt .=$txt;
$included = [];
foreach ($files as $file) {
    if (strpos(strtolower($alltxt), strtolower($file))) {
        $included[] = $file;
    }
}
print_r(array_diff($files, $included));

result: Array ( [1] => 2.jpg [2] => 3.jpg [3] => 4.jpg [4] => 5.jpg )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM