NicsWorld
NicsWorld

Reputation: 21

How to cut only the FIRST character in a string

so I have this situation where I want to cut out the first '1.' out of a string, but not any following '1.'s. I am wondering if this is even possible to do.

So I am converting an it to a string, and I am wondering if there is a way to ONLY cut out the initial '1.' and not any following.

So my script dynamically assigns a number, for example 1, 1.1, 1.2, 2, 3, 3.1 - based on certain criteria. And it was currently adding 1. to the beginning of everything. So 1 would = 1.1, 2.1 would = 1.2.1 so on.

Is there a way to force it to ONLY take out the first and not any following? Here is my source:

 $str = (string)$i; $str = $i;
 $prepend = $parentPrepend ? 
                 $parentPrepend . '.' . $i 
               : $str = ltrim($str, '\1');
 $i++;  

Upvotes: 1

Views: 365

Answers (3)

Mike Dinescu
Mike Dinescu

Reputation: 55720

The reason your ltrim code doesn't work is that you are passing in \1 which is not the same as the character 1. \1 refers to the character whose ASCII code is 1 which is not the same as 1 whose ASCII code is actually \49.

Modify your code like this:

 ltrim($str, '1');

That should trim all 1s from the left of the string.

However, you should know that the ltrim will remove all matching characters from the left of the string, not just the first one!

If you want only the first, then you should use substr instead, with a test to make sure it is a 1.

if(substr($str, 0, 1) == '1')
    $str = substr($str, 1);

And if you want to remove the period too, then simply modify the code to include that (and look at first 2 characters instead of only first character)

if (strlen($str) > 2 && substr($str, 0, 2) == '1.')
    $str = substr($str, 2);

Upvotes: 1

STLMikey
STLMikey

Reputation: 1210

You could also use str_replace with a constraint:

$new_string = str_replace ('1.' , '' , $your_string, 1);

Upvotes: 0

slapyo
slapyo

Reputation: 2991

use strpos to check if 1. is at the beginning. If it is, then use substr to return the string minus the 1.

$string = '1.1';

if (strpos($string, '1.') === 0) {
  $string = substr($string, 2);
}

var_dump($string);

Upvotes: 0

Related Questions