0

I have a string like this:

S="str1|str2|str3"

I want extract another string from S which will contains only

t="str1|str2"

where | is the delimiter

thanks

6 Answers 6

2
$string = "str1|str2|str3";
$pieces = explode( '|', $string); // Explode on '|'
array_pop( $pieces); // Pop off the last element
$t = implode( '|', $pieces); // Join the string back together with '|'

Alternatively, use string manipulation:

$string = "str1|str2|str3";
echo substr( $string, 0, strrpos( $string, '|'));

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

@Zonta You're quite welcome - If the input string is only going to be like your example, use the second version (string manipulation), as it's far more efficient.
yes, my input string is only going to be like my ex, cheers ;)
0
implode("|",  array_slice(explode("|", $s), 0, 2));

Not a very flexible solution, but works for your test case.

Alternatively, you can utilise explode()'s third param limit, like so:

implode("|",  explode("|", $s, -1));

Comments

0
$s = 'str1|str2|str3';
$t = implode('|', explode('|', $s, -1));
echo $t; // outputs 'str1|str2'

Comments

0

So, get the same string without the last element?

This works:

print_r(implode('|', explode('|', 'str1|str2|str3', -1)));

Using explode with a negative limit so it returns all the string without the last element, and then imploding the elements again.

Comments

0

This example should set you on the right path

$str = "str1|str2|str3";
$pcs = explode("|", $str);
echo implode( array_slice($pcs, 0, 2), "|" );

Comments

0

I would take a look at the strpos function and at the substr function.

That is the way I would go about doing it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.