Using the built-in ltrim () PHP module to delete a single character

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

I iterate over an array of strings, and I would like to remove the first and only the first, match (vowels in this case):

 ltrim($value, "aeiouyAEIOUY"); 

In the default behavior, the string aardvark or aardvark will be aardvark as "rdvark" . I would like the result to be "ardvark" .

I am not tied to ltrim by any means, but it seemed like the closest PHP built-in function. It would be nice ltrim , and rtrim had an optional parameter "limit", just saying ... :)

+6
source share
6 answers

Just use preg replace which has a limit.

eg

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

Regular expressions are probably crowded, but:

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

Note that i makes the case insensitive.

+4
source

You cannot use ltrim for this for the reasons you say, and you cannot use str_replace (which also has no restrictions). I think the easiest way is to use a regex:

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

However, if you really do not want to do this, you can use a substring, but you will need to check the position of any of these lines in a line in a loop, since there is no php function that does this check that I know.

+1
source

You can use the preg_replace function:

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

There are several ways to do what you want to do.

Perhaps the easiest would be to replace the regular expression as follows:

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

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

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

Or

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

All Articles