Sunday, August 24, 2008

How to remove first letter from a string using php - substr()

When you need to strip or remove the first letter from a string, the easiest way to do it is to use php substr(). you can use substr() for many purposes look at the php manual here

<?php

$my_text = '12345678';

echo substr($my_text, 1);  // 2345678

?>



Get custom programming done at GetAFreelancer.com!

9 comments:

  1. Hi

    Use substr($my_text,1,strlen($my_text)-1).

    Sheshachaliah

    ReplyDelete
  2. thanks machan..it helped me. im new to PHP.

    ReplyDelete
  3. Hi!
    I want to replace first character of string with last character whatever it is.
    Let say, I have a string:

    $string="0123456";

    I want it to be like this;
    $string="612345";
    and then
    "51234"
    and then
    "4123" and so on.
    How I can do that in php. I am new to php.Thanks

    ReplyDelete
  4. I needed this to construct a complicated MySQL query where the data input had to be really flexible, and the first character of the search term may or may not be available. This trick worked like a charm by letting me try the search with or without the first character. Thanks!

    ReplyDelete
  5. To give an answer to the comment of Anonymous:

    You can replace the first letter of a string by treating the string like an array with each letter being a key of the array. Counting in strings starts at 0. So in order to replace the first letter, you simply do this:

    $string = "abcdef";
    $string[0] = "g";
    echo $string; // will output "gbcdef"

    ReplyDelete
  6. Also you can try the following:
    echo "z".substr($my_text,1,strlen($my_text)-1);

    ReplyDelete
  7. Thank you, very helpful
    Victor

    ReplyDelete
  8. $value = "test content";
    $value = ltrim(rtrim($value, 't'), 't'); // est conten

    ReplyDelete
  9. I have array of numbers (array(08056896869, 08099484948, 08067656789))
    I wish to remove the first 0 from each of the numbers and have the array back. PHP scripter

    ReplyDelete