¿Cómo eliminar el carácter principal de una cadena?

I have a input string like:

$str = ':this is a applepie :) ';

How can I remove the first occurring : con PHP?

Salida deseada: this is a applepie :)

preguntado el 09 de enero de 11 a las 09:01

10 Respuestas

To remove every : from the beginning of a string, you can use ltrim:

$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'

Respondido 31 Oct 15, 20:10

Note that lrtim will remove all :::::. Sometimes this is not desired behavior. - CDR

note that this is only intended for single characters. ltrim will trim all of the characters in the provided string: ltrim('prefixprefix_postfix', 'prefix') resultados en '_postfix'; - Cody Django

"How to remove the first character of string in PHP" was the question and this comment doesn't actually answer that. - Escotilla

La substr() function will probably help you here:

 $str = substr($str, 1);

Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.

respondido 28 mar '16, 20:03

Be aware of unicode. If you're dealing with an arbitrary string (e.g. "Ål <- danish for eel"), you should use mb_substr and specify the encoding. - Thomas Jensen

this is not a correct implementation, it not working with single character string "a". if you try single character string, substr return a boolean value - anru

@anru The manual states if the string length is equal to the start parameter, an empty string will be returned. Prior to version 7, false was returned. So you would need to check if they're equal if that is not the behaviour you want. - rybo111

Utilización de substr:

$str = substr($str, 1); // this is a applepie :)

Respondido el 09 de enero de 11 a las 12:01

Exec time for the 3 answers :

Remove the first letter by replacing the case

$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by �, but ok for echo

Exec time for 1.000.000 tests : 0.39602184295654 AMF


Remove the first letter with substr()

$str = "hello";
$str = substr($str, 1);

Exec time for 1.000.000 tests : 5.153294801712 AMF


Remove the first letter with ltrim()

$str = "hello";
$str= ltrim ($str,'h');

Exec time for 1.000.000 tests : 5.2393000125885 AMF


Remove the first letter with preg_replace()

$str = "hello";
$str = preg_replace('/^./', '', $str);

Exec time for 1.000.000 tests : 6.8543920516968 AMF

respondido 21 mar '14, 19:03

Thanks. See my update, though. It caused a problem for me when using the updated string in an SQL query. - rybo111

Solo probé el $str[0] = ''; solution and it no work. well it does however if you then plan on using the variable for example to compare > or < it won't work. It still counts ` ` as +` for example $str = 'hello'; $str[0] = ''; var_dump($str); // string(5) 'ello' - enero

@Ian: I came across the same issue while fetching records from an API using a keyword, tried var_dump($keyword) which was showing the previous character length.. then I tried trimming the keyword and then it worked fine var_dump(trim($keyword)).. Hope this helps someone.. :) - Syed Qarib

This does not work. The "removed" position is replaced with null byte, so you get "\0hello" instead of "hello". - Josef Kufner

I get "Warning: Cannot assign an empty string to a string offset" for $str[0] = ""; - Francisco Luz

La respuesta aceptada:

$str = ltrim($str, ':');

works but will remove multiple : when there are more than one at the start.

$str = substr($str, 1);

will remove any character from the start.

Sin embargo,

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

funciona perfectamente.

Respondido 05 Feb 18, 04:02

$str = substr($str, 1);

Vea PHP manual example 3

echo substr('abcdef', 1);     // bcdef

Nota:

unset($str[0]) 

no trabajará as you cannot unset part of a string:-

Fatal error: Cannot unset string offsets

Respondido 30 Jul 13, 23:07

Noticias

After further tests, I don't recommend using this any more. It caused a problem for me when using the updated string in a MySQL query, and changing to substr fixed the problem. I thought about deleting this answer, but comments suggest it is quicker somehow so someone might have a use for it. You may find trimming the updated string resolves string length issues.


Sometimes you don't need a function:

$str[0] = '';

Por ejemplo:

$str = 'AHello';
$str[0] = '';
echo $str; // 'Hello'

This method modifies the existing string rather than creating another.

Respondido 15 Feb 16, 14:02

This seems to be quicker too. - Emanuil Rusev

@EmanuilRusev how so? Just curious if you mean it's quicker to type or it runs quicker. - rybo111

Gotta be careful with this. The code below outputs bool(false). $foo = 'book'; $bar = 'book'; $bar = substr($bar, 1); $foo[0] = ''; var_dump($foo === $bar); - thoughtrepo

This doesn't remove the first character. It replaces it with a non printable chr(0). Es equivalente a $str[0] = chr(0);. You can check the string code with var_dump(bin2hex($str)); Conseguirás 0048656c6c6f. See that first 00 ¿byte? - Paul Spiegel

it's 17.61% faster then substr($str, 1) - OzzyCzech

Trims occurrences of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what, $words, $char_list = '') {
    if(!is_array($words)) return false;
    $char_list .= " \t\n\r\0\x0B"; // default trim chars
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b";
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '', trim($what, $char_list))), $char_list);
    return $str;
}

// for example:
$trim_list = array('AND', 'OR');

$what = ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2"

$what = ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC"
?>

respondido 09 mar '12, 16:03

This answer seems to be completely ignoring the OP's question requirements and sample string. This is, at most, the correct answer to a different question. - mickmackusa

use mb_substr function

    mb_substr("我abc", 1);

Respondido 04 Abr '19, 06:04

Useful if the character is a currency symbol. - Raymie

The code works well for me.

$str = substr($str ,-(strlen($str)-1));

Maybe, contribute with answers too.

Respondido el 18 de Septiembre de 14 a las 03:09

this one is not working with single character string: like "a" - anru

You're right =) So, believe that a possible solution would be to test before it only contains one character. For example: $str = strlen($str) > 1 ? substr($str ,-(strlen($str)-1)) : $str; Or $str = strlen($str) > 1 ? substr($str ,-(strlen($str)-1)) : ''; because the idea is to remove the last character, if you only have one ... :P - calraiden

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.