strpos
文字列を検索するとき、針の配列に をどのように使用しますか? 例えば:
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpos($string, $find_letters) !== false)
{
echo 'All the letters are found in the string!';
}
これを使うとうまくいかないので、こういうのがあったらいいな
@Dave http://www.php.net/manual/en/function.strpos.php#107351から更新されたスニペット
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
使い方:
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
if (strposa($string, $array, 1)) {
echo 'true';
} else {
echo 'false';
}
返品させていただきtrue
ますarray
"cheese"
。
更新:最初の針が見つかったときに停止する改善されたコード:
function strposa(string $haystack, array $needles, int $offset = 0): bool
{
foreach($needles as $needle) {
if(strpos($haystack, $query, $offset) !== false) {
return true; // stop on first true result
}
}
return false;
}
$string = 'This string contains word "cheese" and "tea".';
$array = ['burger', 'melon', 'cheese', 'milk'];
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
以下のコードは、それを行う方法を示すだけでなく、使いやすい関数に入れます。それは「ジェスダ」によって書かれました。(ネットで見つけました)
PHP コード:
<?php
/* strpos that takes an array of values to match against a string
* note the stupid argument order (to match strpos)
*/
function strpos_arr($haystack, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false) return $pos;
}
return false;
}
?>
使用法:
$needle = array('something','nothing');
$haystack = "This is something";
echo strpos_arr($haystack, $needle); // Will echo True
$haystack = "This isn't anything";
echo strpos_arr($haystack, $needle); // Will echo False
strpos
を返す場合、配列を反復処理して「フラグ」値を設定できますfalse
。
$flag = false;
foreach ($find_letters as $letter)
{
if (strpos($string, $letter) === false)
{
$flag = true;
}
}
次に の値を確認します$flag
。
特定の文字が実際に文字列に含まれているかどうかを確認したいだけの場合は、strtokを使用します。
$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
// not found
} else {
// found
}
この式は、すべての文字を検索します。
count(array_filter(
array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)
これを試すことができます:
function in_array_strpos($word, $array){
foreach($array as $a){
if (strpos($word,$a) !== false) {
return true;
}
}
return false;
}
次のコードを使用します。
$flag = true;
foreach($find_letters as $letter)
if(false===strpos($string, $letter)) {
$flag = false;
break;
}
次に の値を確認します$flag
。の場合true
、すべての文字が見つかりました。そうでない場合は、false
です。