Question

I want to ask about substr() function. I have a code like this:

<?php    
$word = 'diriku';
    $word2 = $word;
    //first condition
    if ( (substr($word,-3)=="kah") or (substr($word,-3)=="lah") or (substr($word,-3)=="pun") or (substr($word,-3)=="nya"))
{
    $word2 = substr($word,0,-3);
}
    //second condition
else if( (substr($word,-2)=="ku") or (substr($word,-2)=="mu") )
{
    $word2 = substr($word,-2);
}
    echo $word2;
    echo "<br />";
    echo $word;
?>

Result must be : DIRI but I don't know why result is DIR. My opinion is the substr is cut the word at first condition although it's true or false.

So anyone know how to logic compare substr function so if the first condition true, it pass the else, and if cond is false, it continue to else, not always true.

Sorry for this mess explanation.. I don't know how to describe it clearly.

Was it helpful?

Solution

 <?php
        $word = 'songsangkukah';
        $word2 = $word;

        if ( (substr($word,-3)=="kah") or (substr($word,-3)=="lah") or (substr($word,-3)=="pun") or (substr($word,-3)=="nya"))
        {
           $word2 = substr($word, 0 , -3);
        }

        if((substr($word2,-2)=="ku")or(substr($word2,-2)=="mu"))
        {
            $word2 = substr($word2 , 0 , -2);
        }

        echo $word2;
        echo "<br />";
        echo $word;
    ?>

Here you go. the required output.

OTHER TIPS

Please try this.

if ( (substr($word,-3)=="kah") or (substr($word,-3)=="lah") or (substr($word,-3)=="pun") or (substr($word,-3)=="nya"))

It seems that there is something wrong with your 3rd condition's )

Please check your code.

substr($word,-3=="pun"), 

// it should be 

(substr($word,-3)=="pun")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top