>> ZG·Lingua >  >> Language Resources and Tools >> Linguistic Software

Code of find vowels in string php?

```php

function findVowels($string) {

// Define the vowels we're looking for (case-insensitive)

$vowels = ['a', 'e', 'i', 'o', 'u'];

// Initialize an empty array to store found vowels

$foundVowels = [];

// Loop through each character in the string

for ($i = 0; $i < strlen($string); $i++) {

$char = strtolower($string[$i]); // Convert to lowercase for case-insensitive check

if (in_array($char, $vowels)) {

// If the character is a vowel, add it to the array

$foundVowels[] = $char;

}

}

// Return the array of found vowels

return $foundVowels;

}

// Example usage

$string = "This is a test string";

$vowelsFound = findVowels($string);

// Print the found vowels

echo "Vowels found in the string: " . implode(", ", $vowelsFound);

?>

```

Explanation:

1. `findVowels($string)` Function:

- Takes a string as input.

- Defines an array `$vowels` containing lowercase vowels.

- Creates an empty array `$foundVowels` to store the results.

2. Looping through the String:

- Uses a `for` loop to iterate through each character in the string.

- Converts each character to lowercase using `strtolower()` for case-insensitive comparison.

3. Checking for Vowels:

- Uses `in_array()` to check if the current character exists in the `$vowels` array.

- If it's a vowel, adds it to the `$foundVowels` array.

4. Returning the Result:

- Returns the `$foundVowels` array, containing all the vowels found in the input string.

5. Example Usage:

- Defines a sample string `$string`.

- Calls the `findVowels()` function to find the vowels in the string and stores the result in `$vowelsFound`.

- Uses `implode()` to join the vowels in the `$vowelsFound` array with commas and spaces, then prints the result.

This code will output:

```

Vowels found in the string: i, i, a, e, i, a, e

```

Copyright © www.zgghmh.com ZG·Lingua All rights reserved.