Reputation: 79
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.
Upvotes: 0
Views: 68
Reputation: 72269
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
Upvotes: 1
Reputation: 2023
function explode($string)
{
$delimiter = '_';
return explode($delimiter, explode($delimiter, $string, 2)[1], 2);
}
$string = "Makes_me_wonder";
$strings = explode($string);
echo $strings[0]; //me
echo $strings[1]; //wonder
$string = "I_wont_gohome_withoutyou";
$strings = explode($string);
echo $strings[0]; //wont
echo $strings[1]; //gohome_withoutyou
Upvotes: 2
Reputation: 13313
You can use explode with 3rd parameter - limit:
$string = "I_wont_gohome_withoutyou";
$arr = explode("_",$string,3);
$str1 = $arr[1]; //wont
$str2 = $arr[2]; //gohome_withoutyou
Provided that you have two or more _
in a word strictly. If it is so, there needs a work around too.
Upvotes: 2
Reputation: 6251
There are multiple methods but here's one of them.
$pos1 = strpos($string, '_');
$pos2 = strpos($string, '_', $pos1 + 1);
$str1 = substr($string, $pos1 + 1, $pos2 - $pos1 - 1);
$str2 = substr($string, $pos2 + 1);
This assumes that there are at least 2 underscores in the string.
Upvotes: 1