【问题标题】:how to check presence of certain character in a variable using php如何使用php检查变量中是否存在某些字符
【发布时间】:2019-06-05 04:13:40
【问题描述】:

我正在使用下面的代码通过 php 检查某些字符的存在,它工作正常。

使用下面的代码,我可以检查字符 a 是否存在于变量中并且正在工作。

$mystring = 'my food is okay. its delicious';
$findme   = 'a';
$pos = strpos($mystring, $findme);
if ($pos !== false) {
echo 'data found';
}

这是我的问题:我需要检查是否存在多个字符,例如 m,e,s 等。关于如何实现这一点的任何想法。 p>

【问题讨论】:

  • m AND e AND sm OR e OR s ???
  • 是否需要所有字符,或者您只需要确保至少存在一个字符?他们的顺序有关系吗?
  • 非常感谢。它就像魅力一样。你能更新一下,以便我可以选择它作为答案
  • 什么有效?那是一个问题。

标签: php


【解决方案1】:

有很多方法可以做到这一点,从使用多个strpos 到在str_replace 之后进行比较。这里我们可以将字符串拆分成一个数组,并计算与另一个数组的交集:

$mystring = 'my food is okay. its delicious';
$findme   = ['m', 'e', 's'];

检查数组中的任何字符:

if(array_intersect($findme, str_split($mystring))) {
    echo "1 or more found";
}

检查数组中的所有字符:

if(array_intersect($findme, str_split($mystring)) == $findme) {
    echo "all found";
}

为了好玩,通过回调运行数组并根据它是否在字符串中进行过滤。这将检查任何:

if(array_filter($findme, function($v) use($mystring) {
                             return strpos($mystring, $v) !== false;
                         }))
{
    echo "1 or more found";
}

这将检查所有:

if(array_filter($findme, function($v) use($mystring) {
                             return strpos($mystring, $v) !== false;
                         }) == $findme)
{
    echo "all found";
}

【讨论】:

  • !array_diff($findme, str_split($mystring)) 也适用于所有人。
【解决方案2】:

另一种方法是使用trim

$mystring = 'my food is okay. its delicious';
$findme = 'ames';

$any = trim($findme, $mystring) != $findme;
$all = !trim($findme, $mystring);

【讨论】:

    【解决方案3】:

    这个函数会帮你搞定的:

    /**
     * Takes an array of needles and searches a given string to return all
     * needles found in the string. The needles can be words, characters,
     * numbers etc.
     * 
     * @param array $needles
     * @param string $haystack
     * @return array|null
     */
    function searchString(array $needles, string $haystack): ?array
    {
        $itemsFound = [];
        foreach($needles as $needle) {
            if (strpos($haystack, $needle) !== false) {
                $itemsFound[] = $needle;   
            }
        }
    
        return $itemsFound;
    }
    

    https://3v4l.org/5oXGp

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 2018-08-04
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2022-10-17
      • 2011-03-31
      相关资源
      最近更新 更多