Remove First 4 Characters of a String with PHP

Remove first 4 characters of a string with PHP

You could use the substr function to return a substring starting from the 5th character:

$str = "The quick brown fox jumps over the lazy dog."
$str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."

Delete first 3 characters and last 3 characters from String PHP

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

How to remove the leading character from a string?

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

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

php remove n chars from nth index of a string

$input = 'asdqwe123jklzxc';
echo str_replace(substr($input, 3, 8), '', $input);

Demo

How to remove first n numeric characters from a string using PHP?

Use the limit parameter with preg_replace:

$str = preg_replace('~\d~', '', $str, 5);

How can I remove three characters at the end of a string in PHP?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr documentation:

If length is given and is negative, then that many characters will be omitted from the end of string

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.



Related Topics



Leave a reply



Submit