Home » Php » string – Use of PHP built-in ltrim() to remove a single character

string – Use of PHP built-in ltrim() to remove a single character

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a simple way to use ltrim() to remove a single instance of a match instead of all matches?

I’m looping through array of strings and I’d like to remove the first, and only first, match (vowels in this case):

ltrim($value, "aeiouyAEIOUY");

With default behavior the string aardvark or Aardvark would be trimmed to be "rdvark". I’d like result to be "ardvark".

I’m not bound to ltrim by any means but it seemed the closest built-in PHP function. It would be nice of ltrim and rtrim had an optional parameter “limit”, just saying… 🙂

How to&Answers:

Just use preg replace it has a limit option

eg

$value = preg_replace('/^[aeiouy]/i', '', $value, 1); 

Answer:

Regular expressions is probably overkill, but:

$value = preg_replace('/^[aeiouy]/i', '', $value);

Note the i makes it case-insensitive.

Answer:

You can’t use ltrim to do this for the reasons you say, nor can you use str_replace (which also has no limit). I think it’s easiest just to use a regex:

$value = preg_replace('/^[aeiouy]/i', '', $value);

However if you really don’t want to do that, you can use a substring, but you would have to check the position of any of those strings in the string in a loop as there is no php function that does such a check that I know of.

Answer:

You can use the preg_replace function:

<?php
    $value = preg_replace('/^[aeiouy]/i', '', $value);
?>

Answer:

There are several way you can go about doing what you are looking to do.

Perhaps most straightforward would be a regular expression replacement like this:

$pattern = '/^[aeiouy]{1}/i';
$result = preg_replace($pattern, '', $original_string);

Answer:

This is probably the most efficient way (so ignore my regular expressions answer):

if (strpos('aeiouyAEIOUY', $value[0]) !== false) $value = substr($value, 1);

Or,

if (stripos('aeiouy', $value[0]) !== false) $value = substr($value, 1);