0

I have a string which I have exploded, it starts like this,

|Crime|Drama|Mystery|Suspense|Thriller|

I would like to remove the first | and the last | after exploding so that the exploded text can look like this

Crime,Drama,Mystery,Suspense,Thriller

is this possible to do?

here is my code so far.

<?php $explodegen = explode("|", $val->Genre); ?>
<?php
foreach($explodegen as $exploding){
echo "".$exploding.",";
} 
?>
0

6 Answers 6

4
substr($string, 1, -1);

Then explode it.

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

Comments

1

You have multiple options then:

  • trim() the input to strip the | before exploding.

  • Or array_filter on the result array to have the empty results removed.

  • If it's just for output use strtr to to transform | into , (and apply trim beforehand).

I'd personally rather extract the strings using preg_match_all("/[^|]+/").

2 Comments

I gotta disagree with preg_match_all for this use case. It's quite cumbersome: First you have to pass it a reference object to put the result in, then you have to dig into that object's internals to actually get the desired data out.
Actually all of the the splitting+rejoining variations are pointless, since it's just for converting the delimiter prior outputting.
0
$input = '|Crime|Drama|Mystery|Suspense|Thriller|';
$delim = '|';
$exploded = explode($delim, trim($input, $delim));
echo implode(',', $exploded);

You should get

Crime,Drama,Mystery,Suspense,Thriller

Comments

0

Lots of ways to do this. Here's one option:

$str = "|Crime|Drama|Mystery|Suspense|Thriller|";

echo $str = str_replace("|", ",", trim($str, "|"));

Result:

Crime,Drama,Mystery,Suspense,Thriller

See demo

Comments

0
  1. preg_split with the PREG_SPLIT_NO_EMPTY flag: preg_split('/\|/', $in, PREG_SPLIT_NO_EMPTY);
  2. array_filter and explode: array_filter(explode('|', $in));
  3. explode and trim: explode('|', trim($in, '|'));

Option 1 is the only one that you can do in a single function call. Option 3, however, is the only one that keeps empty elements if they are in the middle of the string.

Comments

0

trim($string, "|") would remove comma from the beginning and end of a string.

and

rtrim($string, "|") would remove comma from the end of a string.

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.