【问题标题】:How to check/find if multiple letters are in a string | PHP如何检查/查找字符串中是否有多个字母 | PHP
【发布时间】:2021-03-06 18:50:14
【问题描述】:

到目前为止,我设法找到一个字母是否在任何给定的字符串中。但是,我无法设法要求多个条件,例如 'a' && 'e' && 'i'... 所有这些字母都需要在字符串中,以便回显“找到元音”。

我已经尝试过使用 stristr、strpos... 到目前为止,我最好的猜测已被弃用,因此我无法使用它。 我的最后一个资源,无论如何都不起作用,是嵌套 if 条件使其起作用;还尝试了没有正面结果的数组。

$string = 'murcielago'; // a word with 5 vowels
if (stristr($string, 'a') == TRUE) {
    echo 'Vowel found';
} else {
    echo "Vowel not found";
}

这是我在原始给定字符串中找到一个字符串或字母的代码。

【问题讨论】:

  • 所以你只想检查字符串中是否有元音?顺序或是否有两个或更多都无关紧要。您只想检查字符串中是否有单个元音或多个元音?
  • 是的。类似于: if letter 'a' && 'b' %% 'c' in $string: echo "all those letters are in the string";到目前为止,我看到一个函数在给定单词上找到“字符串”(在这种情况下为元音)时会给你 1,所以我只是在寻找一种所有条件都为 TRUE 的方法,以便为回显提供绿灯。现在我要弄清楚如何简化它。

标签: php string if-statement


【解决方案1】:

这让我想得更远了!明白了。

$string = "murcielago";

if (strpos($string,'a') && strpos($string,'e') && strpos($string,'i') && strpos($string,'o') && strpos($string,'u') == true) 
{
 echo "nailed it";
} else { 
         echo "No vowels for you"; 
       } 
´´´

I wonder if there is any way to make all the conditions into one since I am still using the same strpos function.

【讨论】:

    【解决方案2】:

    尝试使用正则表达式和preg_match

    <?php
            //Enter your code here, enjoy!
    
    $string = 'murcielago';
    
    // This will echo "vowel found"
    if(preg_match( '`[aeiouy]`', $string)){
       
        echo "vowel found\n";
    }
    
    $string2 = 'bcdfgplk';
    
    // This won't echo anything
    if(preg_match( '`[aeiouy]`', $string2 )){
        echo "vowel not found\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2013-04-01
      • 1970-01-01
      • 2014-04-22
      • 2014-01-01
      • 1970-01-01
      • 2020-12-12
      相关资源
      最近更新 更多