Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first and last char from string

Tags:

php

trim

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?

like image 462
user248488 Avatar asked Sep 11 '10 09:09

user248488


People also ask

How do I remove the last character of a string?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.


2 Answers

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.

like image 88
NikiC Avatar answered Sep 26 '22 21:09

NikiC


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)); 
like image 35
Bojoer Avatar answered Sep 26 '22 21:09

Bojoer