在 strpos 中使用数组作为针

发布于 2024-11-14 10:11:25 字数 265 浏览 3 评论 0原文

在搜索字符串时,如何将 strpos 用于针数组?例如:

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpos($string, $find_letters) !== false)
{
    echo 'All the letters are found in the string!';
}

因为用这个的时候不行,如果有这样的就好了

How do you use the strpos for an array of needles when searching a string? For example:

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpos($string, $find_letters) !== false)
{
    echo 'All the letters are found in the string!';
}

Because when using this, it wouldn't work, it would be good if there was something like this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

不忘初心 2024-11-21 10:11:25

@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, $needle, $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

@Dave an updated snippet from 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);
}

How to use:

$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');

if (strposa($string, $array, 1)) {
    echo 'true';
} else {
    echo 'false';
}

will return true, because of array "cheese".

Update: Improved code with stop when the first of the needles is found:

function strposa(string $haystack, array $needles, int $offset = 0): bool 
{
    foreach($needles as $needle) {
        if(strpos($haystack, $needle, $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
固执像三岁 2024-11-21 10:11:25

str_replace 速度要快得多。

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);

str_replace is considerably faster.

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
川水往事 2024-11-21 10:11:25

下面的代码不仅展示了如何做到这一点,而且还将其放入一个易于使用的函数中。它的作者是“杰斯达”。 (我在网上找到的)

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 

The below code not only shows how to do it, but also puts it in an easy to use function moving forward. It was written by "jesda". (I found it online)

PHP Code:

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

Usage:

$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 
北音执念 2024-11-21 10:11:25

问题是,提供的示例只是一个“示例”还是您正在寻找的内容?这里有很多混合的答案,我不明白公认的答案的复杂性。

要查明字符串中是否存在针数组的任何内容,并快速返回 true 或 false:

$string = 'abcdefg';

if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
    echo 'at least one of the needles where found';
};

如果是,请给出@Leon 功劳。

找出字符串中是否存在针数组的所有,在本例中,所有三个'a'、'b''c' 必须存在,就像您提到的作为您的“例如”

echo '在字符串中找到所有字母!';

这里的许多答案都脱离了这种背景,但我怀疑您标记为已解决的问题的意图。例如,接受的答案是

$array  = array('burger', 'melon', 'cheese', 'milk');

如果所有这些单词必须在字符串中找到怎么办?

然后您在此页面上尝试一些“未接受的答案”

The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.

To find out if ANY content of the array of needles exists in the string, and quickly return true or false:

$string = 'abcdefg';

if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
    echo 'at least one of the needles where found';
};

If, so, please give @Leon credit for that.

To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b' and 'c' MUST be present, like you mention as your "for example"

echo 'All the letters are found in the string!';

Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of

$array  = array('burger', 'melon', 'cheese', 'milk');

What if all those words MUST be found in the string?

Then you try out some "not accepted answers" on this page.

染墨丶若流云 2024-11-21 10:11:25

如果 strpos 返回 false,您可以迭代该数组并设置一个“标志”值。

$flag = false;
foreach ($find_letters as $letter)
{
    if (strpos($string, $letter) !== false)
    {
        $flag = true;
    }
}

然后检查$flag的值。

You can iterate through the array and set a "flag" value if strpos returns false.

$flag = false;
foreach ($find_letters as $letter)
{
    if (strpos($string, $letter) !== false)
    {
        $flag = true;
    }
}

Then check the value of $flag.

失与倦" 2024-11-21 10:11:25

如果您只想检查字符串中是否确实存在某些字符,请使用 strtok

$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
    // not found
} else {
    // found
}

If you just want to check if certain characters are actually in the string or not, use strtok:

$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
    // not found
} else {
    // found
}
谜泪 2024-11-21 10:11:25

此表达式搜索所有字母:

count(array_filter( 
    array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)

This expression searches for all letters:

count(array_filter( 
    array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)
誰ツ都不明白 2024-11-21 10:11:25

你可以试试这个:

function in_array_strpos($word, $array){

foreach($array as $a){

    if (strpos($word,$a) !== false) {
        return true;
    }
}

return false;
}

You can try this:

function in_array_strpos($word, $array){

foreach($array as $a){

    if (strpos($word,$a) !== false) {
        return true;
    }
}

return false;
}
深爱成瘾 2024-11-21 10:11:25

您还可以尝试使用 strpbrk() 进行否定(没有字母已找到):

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpbrk($string, implode($find_letters)) === false)
{
    echo 'None of these letters are found in the string!';
}

You can also try using strpbrk() for the negation (none of the letters have been found):

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';

if(strpbrk($string, implode($find_letters)) === false)
{
    echo 'None of these letters are found in the string!';
}
网白 2024-11-21 10:11:25

这是我的方法。迭代字符串中的字符,直到找到匹配项。在更大的针头阵列上,这将优于可接受的答案,因为它不需要检查每根针头来确定是否已找到匹配项。

function strpos_array($haystack, $needles = [], $offset = 0) {
    for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
        if (in_array($haystack[$i],$needles)) {
            return $i;
        }
    }
    return false;
}

我将其与已接受的答案进行了基准测试,并且对于超过 7 个 $needles 的数组,这显着更快。

This is my approach. Iterate over characters in the string until a match is found. On a larger array of needles this will outperform the accepted answer because it doesn't need to check every needle to determine that a match has been found.

function strpos_array($haystack, $needles = [], $offset = 0) {
    for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
        if (in_array($haystack[$i],$needles)) {
            return $i;
        }
    }
    return false;
}

I benchmarked this against the accepted answer and with an array of more than 7 $needles this was dramatically faster.

风和你 2024-11-21 10:11:25

如果我只是想找出大海捞针中是否存在任何针,我使用

可重用函数

function strposar($arrayOfNeedles, $haystack){
  if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
     return strpos($haystack, $needle) !== false;
   })) > 0){
    return true;
  } else {
    return false;
  }
}

strposar($arrayOfNeedles, $haystack); //returns true/false

或 lambda 函数

  if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
     return strpos($haystack, $needle) !== false;
   })) > 0){
     //found so do this
   } else {
     //not found do this instead
   }

If i just want to find out if any of the needles exist in the haystack, i use

reusable function

function strposar($arrayOfNeedles, $haystack){
  if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
     return strpos($haystack, $needle) !== false;
   })) > 0){
    return true;
  } else {
    return false;
  }
}

strposar($arrayOfNeedles, $haystack); //returns true/false

or lambda function

  if (count(array_filter($arrayOfNeedles, function($needle) use($haystack){
     return strpos($haystack, $needle) !== false;
   })) > 0){
     //found so do this
   } else {
     //not found do this instead
   }
花落人断肠 2024-11-21 10:11:25

使用以下代码:

$flag = true;
foreach($find_letters as $letter)
    if(false===strpos($string, $letter)) {
        $flag = false; 
        break;
    }

然后检查$flag的值。如果为true,则已找到所有字母。如果不是,则为 false

With the following code:

$flag = true;
foreach($find_letters as $letter)
    if(false===strpos($string, $letter)) {
        $flag = false; 
        break;
    }

Then check the value of $flag. If it is true, all letters have been found. If not, it's false.

初相遇 2024-11-21 10:11:25

我正在写一个新答案,希望可以帮助任何寻找与我类似的人。

这适用于“我有多个针,我试图用它们来找到一个单独的字符串”的情况。这就是我遇到的问题。

    $i = 0;
    $found = array();
    while ($i < count($needle)) {
        $x = 0;
        while ($x < count($haystack)) {
            if (strpos($haystack[$x], $needle[$i]) !== false) {
                array_push($found, $haystack[$x]);
            }
            $x++;
        }
        $i++;
    }

    $found = array_count_values($found);

数组 $found 将包含所有匹配针的列表,数组中具有最高计数值的项目将是您要查找的字符串,您可以通过以下方式获取:

print_r(array_search(max($found), $found));

I'm writing a new answer which hopefully helps anyone looking for similar to what I am.

This works in the case of "I have multiple needles and I'm trying to use them to find a singled-out string". and this is the question I came across to find that.

    $i = 0;
    $found = array();
    while ($i < count($needle)) {
        $x = 0;
        while ($x < count($haystack)) {
            if (strpos($haystack[$x], $needle[$i]) !== false) {
                array_push($found, $haystack[$x]);
            }
            $x++;
        }
        $i++;
    }

    $found = array_count_values($found);

The array $found will contain a list of all the matching needles, the item of the array with the highest count value will be the string(s) you're looking for, you can get this with:

print_r(array_search(max($found), $found));
柠檬心 2024-11-21 10:11:25

回复@binyamin和@Timo..(没有足够的点来添加评论..)但结果不包含位置..
下面的代码将返回第一个元素的实际位置,这就是 strpos 的目的。如果您希望找到 1 个匹配项,这很有用。如果您希望找到多个匹配项,则第一个找到的位置可能毫无意义。

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
      $res=strpos($haystack, $query, $offset);
      if($res !== false) return $res; // stop on first true result
    }
    return false;
}

Reply to @binyamin and @Timo.. (not enough points to add a comment..) but the result doesn't contain the position..
The code below will return the actual position of the first element which is what strpos is intended to do. This is useful if you're expecting to find exactly 1 match.. If you're expecting to find multiple matches, then position of first found may be meaningless.

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
      $res=strpos($haystack, $query, $offset);
      if($res !== false) return $res; // stop on first true result
    }
    return false;
}
池木 2024-11-21 10:11:25

只是上述答案的升级

function strsearch($findme, $source){
    if(is_array($findme)){
        if(str_replace($findme, '', $source) != $source){
            return true;
        }
    }else{
        if(strpos($source,$findme)){
            return true;
        }
    }
    return false;
}

Just an upgrade from above answers

function strsearch($findme, $source){
    if(is_array($findme)){
        if(str_replace($findme, '', $source) != $source){
            return true;
        }
    }else{
        if(strpos($source,$findme)){
            return true;
        }
    }
    return false;
}
二智少女 2024-11-21 10:11:25
<?php
$Words = array("hello","there","world");
$c = 0;

    $message = 'Hi hello';
     foreach ($Words as $word):
        $trial = stripos($message,$word);
        
        if($trial != true){
            $c++;
            echo 'Word '.$c.' didnt match <br> <br>';
        }else{
            $c++;
            echo 'Word '.$c.' matched <br> <br>';
        }
     endforeach;
     ?>

我用这种代码来检查 hello,它还有编号功能。
如果您想在需要用户键入的网站中进行内容审核实践,则可以使用此选项

<?php
$Words = array("hello","there","world");
$c = 0;

    $message = 'Hi hello';
     foreach ($Words as $word):
        $trial = stripos($message,$word);
        
        if($trial != true){
            $c++;
            echo 'Word '.$c.' didnt match <br> <br>';
        }else{
            $c++;
            echo 'Word '.$c.' matched <br> <br>';
        }
     endforeach;
     ?>

I used this kind of code to check for hello, It also Has a numbering feature.
You can use this if you want to do content moderation practices in websites that need the user to type

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文