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... :)
Just use preg replace it has a limit option
eg
$value = preg_replace('/^[aeiouy]/i', '', $value, 1);
Regular expressions is probably overkill, but:
$value = preg_replace('/^[aeiouy]/i', '', $value);
Note the i makes it case-insensitive.
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.
You can use the preg_replace function:
<?php
$value = preg_replace('/^[aeiouy]/i', '', $value);
?>
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);
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);
Related
I have the following in a variable, |MyString|
I want to strip the leading | and the ending | returning MyString
What is the quickest and non intensive way of doing this?
Easiest way is probably
$result = trim($input, '|');
http://docs.php.net/trim
e.g.
<?php
$in = '|MyString|';
$result = trim($in, '|');
echo $result;
prints MyString
Checkout the str_replace function in PHP http://php.net/manual/en/function.str-replace.php
this should remove all '|' characters:
str_replace('|','',$myString)
You may be able to use a regular expression to only remove the first and last '|' or alternatively using the String trim() function may also work:
http://www.php.net/manual/en/function.trim.php
So, something like this:
$trimmedMyString = trim($myString, "|");
Worth trying anyway.
I need cut from page url www. using php trim() function.
But this function cut and first letter, why?
$domain = parse_url('http://wordpresas.com/page/1');
$domain['host'] = trim($domain['host'], 'www.');
pr($domain['host']); //ordpresas.com
As other have stated the second parameter of trim() contains a list of characters which get trimmed.
However you can use preg_replace() for this. This will make sure only www. will be stripped if the string starts with it.
preg_replace('/^www./', '', $domain['host']);
The most effective way to do this is probably:
if( strncmp( 'www.', $domain['host'], 4) == 0){
$domain['host'] = substr( $domain['host'], 4);
}
It should have complexity O(1) :)
Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?
It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.
But in the meantime, you can use rtrim() to trim all numbers off of the right side.
$val = rtrim($val, '0123456789');
Examples
Input Output
nameofproject1001 nameofproject
nameofproject nameofproject
n4me0fproj3ct1001 n4me0fproj3ct
for string like, project12V123, It is better to do this
$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);
Will return:
Project12V
or use rtrim:
$text = rtrim($text,'0123456789');
You should definitely use regular expressions:
$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";
preg_replace('/[^a-z]/i', '', $string);
I'm not too great at preg_match yet and I was wondering if someone could give me a hand.
I have an array of values e.g. array("black*", "blue", "red", "grey*") I need to find the values with a * at the end then return the word before it.
I believe preg_match() is the best way of doing it but I'm open to suggestions.
Thanks in advanced!
If you must use a regex...
$words = array_map(function($word) {
return preg_replace('/\*\z/', '', $word);
}, $arr);
CodePad.
...but you're probably better off not using regex and using something like...
$words = array_map(function($word) {
return rtrim($word, '*');
}, $arr);
CodePad.
If you want to return only the words which have a trailing *, try something like this first...
$words = preg_grep('/\*\z/', $arr);
CodePad.
The only disadvantage with this (as mentioned in the comments) is PHP will iterate twice over the array. You can simply use a foreach loop to do both of these in one loop if you wish.
Also, it is worth mentioning anonymous functions are a PHP 5.3 thing. You can still most of this code, just separate the functions into their own named functions and pass a reference to them.
If you always have an array like that (i.e. no complex strings, just word*), you really shouldn't use regular expressions, it's an overkill.
Use string functions, like strpos for searching and str_replace or rtrim for removing *.
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
— from str_replace manual
Don't need to use preg_match for this - simple char lookup on the string will work:
$words = array('red*', 'grey', 'white', 'green*');
$return = array();
foreach ($words as $word) {
if ($word[strlen($word) - 1] === '*') {
$return[] = substr($word, 0, -1);
}
}
var_dump($return);
assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
filter_var
flags for the filters
e.g. to get just numbers from the given string
<?php
$a = '!a-b.c3#j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
Edit:
1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].
You can use a regular expression to remove any character that is not a digit:
preg_replace('/\D/', '', $str)
Here the pattern \D describes any character that is not a digit (complement to \d).
Use PHP FILTER functions if you are using PHP 5.2.X, 5.3.x,5.4 . Its highly recommended
$mixed_input = "e3r4t5";
$only_numbers = filter_var($mixed_input, FILTER_SANITIZE_NUMBER_INT);
Please Go through with this link to know more
Replace everything that isn't a number and use that value.
$str = "foo1bar2baz3";
$num = intval(preg_replace("/[^0-9]/", "", $str));
You could use the following function:
function extract_numbers($string) {
preg_match_all('/([\d]+)/', $string, $match);
return $match;
}