Dizi bir dize içinde olup olmadığını kontrol edin

5 Cevap php
$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = some_function_name($comment,$words);
($lin=3)

I substr_count() çalıştı, ama o dizide çalışmaz. Bunu yapmak için yerleşik bir işlevi var mı?

5 Cevap

I array_filter(). Bu PHP> = 5.3 çalışacaktır kullanmak istiyorsunuz. Bir alt sürümü için, farklı şekilde geri arama işlemek gerekir.

$lin = sum(array_filter($words, function($word) use ($comment) {return strpos($comment, $word) !== false;}));

Bu kodun daha hatları ile basit bir yaklaşımdır:

function is_array_in_string($comment, $words)
{
    $count = 0;
    foreach ($comment as $item)
    {
        if (strpos($words, $item) !== false)
            count++;
    }
    return $count;
}

array_map, muhtemelen çok daha temiz bir kod üretecektir.

kullanarak array_intersect & explode,

tüm orada kontrol etmek için:

count(array_intersect(explode(" ", $comment), $words)) == count($words)

saymak:

count(array_unique(array_intersect(explode(" ", $comment), $words)))

Ben burada regex kullanarak downvoted olsun eğer ben şaşırmam, ama burada bir tek-liner rota var:

$hasword = preg_match('/'.implode('|',array_map('preg_quote', $words)).'/', $comment);

(Sadece PHP 5.3 ile çalışan) bir kapatma kullanarak yapabilirsiniz:

$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = count(array_filter($words,function($word) use ($comment) {return strpos($comment,$word) !== false;}));

Ya da basit bir şekilde:

$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = count(array_intersect($words,explode(" ",$comment)));

Sözcükler arasında mükemmel bir uyum varsa sadece dönecektir ikinci şekilde, substringler kabul edilmeyecektir.