André Oliveira
André Oliveira

Reputation: 1123

Checking if string contain values from an Array in PHP

I'm using PHP 7.1.12 and I trying to check if values from an array are present in a string to do that I'm doing this:

public function checkWords($word) {
    $list = array('extinção','desativação','obrigatório');

    foreach($list as $l) {
        if (stripos($word, $l) !== false) {
            return true;
        } 
    }
    return false;
}

and them I call the function

echo($this->checkWords('Físicaem desativação/extinção voluntária:23000.010237/2012-46''); //returns false

Now comes the weird part, if I go to the function and replace $l with let's say: 'hello'.

public function checkWords($word) {
        $list = array('extinção','desativação','obrigatório');

        foreach($list as $l) {
            if (stripos($word, 'extinção') !== false) {
                return true;
            } 
        }

    }

the function call will return true

echo($this->checkWords('Físicaem desativação/extinção voluntária:23000.010237/2012-46''); //returns true

Any ideas?

Upvotes: 0

Views: 137

Answers (3)

B. Desai
B. Desai

Reputation: 16436

When you have to deal with multi-byte characters at that time simple string function will not work. You have to use mb functions for it. There is list of mb functions which work with multi-byte characters, Check entire list here:

http://php.net/manual/en/ref.mbstring.php

Now for find position you can use mb_stripos function. Try below code:

function checkWords($word) {
    $list = array('extinção','desativação','obrigatório');
    foreach($list as $l) {
        if (mb_stripos($word, $l) !== false) {
            return true;
        } 
    }
    return false;
}

var_dump(checkWords('Físicaem desativação/extinção voluntária:23000.010237/2012-46')); // return true
echo PHP_EOL;
var_dump(checkWords('Físicaema dessativação/extsinção voluntária:23000.010237/2012-46')); //return false

DEMO

Upvotes: 0

albert
albert

Reputation: 4468

This seems to be an issue with the string encoding.

1) Check if using mb_stripos works. http://php.net/manual/en/function.mb-stripos.php

2) if (1) fails you may be serving the file with the wrong encoding. Check if your file charset matches your html charset meta header. https://developer.mozilla.org/en/docs/Web/HTML/Element/meta

<meta charset="utf-8">

Upvotes: 1

Randall Valenciano
Randall Valenciano

Reputation: 583

Since this question has a bounty, cannot flag it as duplicate, but the issue is with the function used in your case:

stripos($word, 'extinção')

As here is stated, stripos doesn't handle special characters very well and produces this non deterministic results. Use mb_strpos instead.

Upvotes: 2

Related Questions