PHP Noob PHP Noob - 5 months ago 15
PHP Question

Separation of string into multiple string value

I have a string with

underscores(_)
. What I want is to get the string value after the first underscore and considered as the first string value and the second string value will be the whole string after the underscore of the first string value using
php
.

Example:

$string = "Makes_me_wonder";


Result I want:

$str1 = "me";
$str2 = "wonder";


Another variable I am having:

$string = "I_wont_gohome_withoutyou";


Result should be:

$str1 = "wont";
$str2 = "gohome_withoutyou";


Another one:

$string = 'Never_gonna_leave_this_bed";


Output i want:-

$str1 = "gonna_leave";
$str2 = "this_bed";


Please help me. Thanks.

Answer

I think your solution is like this:-

<?php
function getfinal_result($string){
    $final_data = explode('_',$string,2)[1]; // explode with first occurrence of _ and leave first word
    if(substr_count($final_data,'_')>2){ // now check  _ remains  is greater that 2
        $first_data = substr($final_data , 0, strpos($final_data , '_', strpos($final_data , '_')+1)); // find the string comes after second _
        $second_data = str_replace($first_data.'_','',$final_data); // get the string before the second _
        $last_data = Array($first_data,$second_data); // assign them to final data
    }else{
        $last_data = explode('_',$final_data,2); // directly explode with first occurance of _
    }
    return $last_data; // return final data

}
$first_data = getfinal_result('Makes_me_wonder');
$second_data = getfinal_result('I_wont_gohome_withoutyou');
$third_data = getfinal_result('Never_gonna_leave_this_bed');

echo "<pre/>";print_r($first_data);
echo "<pre/>";print_r($second_data);
echo "<pre/>";print_r($third_data);
?>

Output:- https://eval.in/593240

Comments