Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete first 3 characters and last 3 characters from String PHP

I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both first and last characters i'm not sure if I can actually use this. Any suggestions?

like image 478
Howdy_McGee Avatar asked Aug 12 '11 19:08

Howdy_McGee


People also ask

How can I remove last 3 characters from a string in PHP?

To remove the last three characters from a string, we can use the substr() function by passing the start and length as arguments.

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.

How do I remove the first 4 characters of a string?

Strings are immutable in JavaScript. Alternatively, you can use the slice() method. Use the String. slice() method to remove the first N characters from a string, e.g. const result = str.

How do I remove the first and last character of a string in PHP?

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.


2 Answers

Pass a negative value as the length argument (the 3rd argument) to substr(), like:

$result = substr($string, 3, -3); 

So this:

<?php $string = "Sean Bright"; $string = substr($string, 3, -3); echo $string; ?> 

Outputs:

n Bri
like image 106
Sean Bright Avatar answered Sep 21 '22 19:09

Sean Bright


Use

substr($var,1,-1) 

this will always get first and last without having to use strlen.

Example:

<?php     $input = ",a,b,d,e,f,";     $output = substr($input, 1, -1);     echo $output; ?> 

Output:

a,b,d,e,f

like image 27
James Avatar answered Sep 24 '22 19:09

James