The left of the 3rd delimiter

$var='a_b_c_d_e_f';

I have a variable “$var” like the above.
And its modification like the below.

$left_of_the_first_delimiter= array_shift(explode('_', $var));
$right_of_the_last_delimiter=array_pop(explode('_', $var));

I can get the left of the first delimiter “a” and the right of the last delimiter “f” with the code above.

Now I like the get the left of the last delimiter “a_b_c_d_e”.
So I made the the code below.

$left_of_the_last_delimiter= str_replace('_'.array_pop(explode('_', $var)), '', $var);

So far so good.

Can I get the left of the third delimeter “a_b_c” with your help?

yes.

Think in array terms, which element is the “left of the last delimiter” with respect to the array index?

Would you rephrase the above for me?

The code below is a basic form of an array.

$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

How can I make $var=‘a_b_c_d_e_f’ into array?

Which array index is the “left of the last delimiter”?

Same way you did before.

Do you mean the code below?

$left_of_the_last_delimiter= str_replace('_'.array_pop(explode('_', $var)), '', $var);

Yes.

The code below produces my target result “a_b_c”.

$var='a_b_c_d_e_f';

$last_of_the_delimiter=array_pop(explode('_', $var));

$var1=str_replace('_'.$last_of_the_delimiter, '', $var);

$last1_of_the_delimiter=array_pop(explode('_', $var1));

$var2=str_replace('_'.$last1_of_the_delimiter, '', $var1);

$last2_of_the_delimiter=array_pop(explode('_', $var2));

$var3=str_replace('_'.$last2_of_the_delimiter, '', $var2);

echo $var3.'<br>';

it is fine.for the answer to my original question.

but
How about the origin $var is, I am so sorry, "a_b_c_d_e_f_g_h_i’;?
and I like to find "the left of the 4th delimiter “a_b_c_d”?

I mean that I like to find the left of the "$i"th delimiter out like the code below under the condition of that I don’t know how many delimiter is in the original $var.

$i=3; // $i can be 4 or 5

Can I find any better way for that with your help?

http://php.net/array-slice

This smells really bad of an XY Problem. OP, how about telling us WHY you have a variable like that. Tell us what the real problem is instead of your attempt at solving it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.