42

I have this:

$dataList = "*one*two*three*";
$list = explode("*", $dataList);
echo"<pre>";print_r($list);echo"</pre>";

which outputs:

> Array (
>     [0] => 
>     [1] => one
>     [2] => two
>     [3] => three
>     [4] =>  )

How do I strip the fist and last * in the string before exploding?

NikiC
  • 100,734
  • 37
  • 191
  • 225
user248488
  • 435
  • 1
  • 4
  • 6

5 Answers5

63

Using trim:

trim($dataList, '*');

This will remove all * characters (even if there are more than one!) from the end and the beginning of the string.

NikiC
  • 100,734
  • 37
  • 191
  • 225
56

Some other possibilities:

Using substr:

$dataList = substr($dataList, 1, -1);

You can also choose to not remove the * from the string but rather remove the empty array values which will always be the first and last element. Using array functions array_pop() and array_shift():

$arrData = array_pop(array_shift($arrData));
Bojoer
  • 561
  • 4
  • 4
  • 1
    Second part is incorrect and results in an error. `array_pop` and `array_shift` modify the array itself (return value for both is the element they remove), so you simply need to do `array_shift($arrData); array_pop($arrData);` – Headbank Dec 30 '20 at 20:53
17

$string = substr($dataList, 1, -1);

Remove the first and the last character of the string in php

Mark Melgo
  • 1,477
  • 1
  • 13
  • 30
Syed Sxxis
  • 171
  • 1
  • 2
7
trim($dataList, "*")
reko_t
  • 55,302
  • 10
  • 87
  • 77
2
echo trim($dataList,"*");

hope this solve your problem

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143