string - Words syllables in php

909

guys I'm new in PHP, so please HELP! Thank you. Lets say I need to syllable some, not typical words: text= "abce dfia jicd fbii". Condition is: if we have two consonants near each other in text, like "bc","df","cd" or "fb", we need to split them with insert "-". So output must to be: "ab-ce d-fia jic-d f-bii". And my output is: "abcei-idfiai-ijicdi-ifbii". What I do wrong? Please help!

$text= "abce dfia jicd fbii";
$letters_1= array("a","e","i","j");
$letters_2= array("b","c","d","f");
$insert= "-";

    for ($x=0; $x<strlen($text); $x++) {
        foreach($letters_2 as $letter => $value) {
            if ($letter==$text[$x] and $value==$value) {
                $new_text= str_replace(" ", $text[$x].$insert.$text[$x], $text);
            }
        }
    }
echo $new_text;

I expect the output: "ab-ce d-fia jic-d f-bii"

677

Answer

Solution:

I'd use a regular expression for this. As far as I'm aware, there's no shorthand for "consonants only", so we'll need to build that expression ourselves. Looking at the fulla-z range, excluding vowels and using ranges where possible, that gives usb-d,f-h,j-n,p-t andv-z as consonant ranges (if you wanty to be treated as a vowel, usev-x andz instead ofv-z).

So something like this should work (there may be a shorter or more efficient expression to do this):

$new_text = preg_replace('/([b-df-hj-np-tv-z])([b-df-hj-np-tv-z])/i', '$1-$2', $text);

var_dump($new_text);
// string(23) "ab-ce d-fia jic-d f-bii"

People are also looking for solutions to the problem: php - Calling the function inside helper file

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.