简体   繁体   中英

How to check/find if multiple letters are in a string | PHP

So far, I managed to find if ONE letter is in ANY given string. However, I cannot manage to ask for multiple conditions like 'a' && 'e' && 'i'... In a way that all of those letter need to be in the string so the echo "Vowel found" gets out.

I have tried with stristr, strpos... and so far my best guess was deprecated so I couldn't use it. My last resource, which didn't work anyway, was to nest if conditions to make it work; also tried with arrays with no positive result.

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

This is my code for ONE string or letter to be found in the original given string.

It made me think further! Got it.

$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.

Try using a regex and 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM