I have strings:
17s 283ms
48s 968ms
The string values are never the same and I want to extract the "second" value from it. In this case, the 17 and the 48.
I'm not very good with regex, so the workaround I did was this:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
The problem is, the character 's' exists in both split_str[0] and split_str[1], so my $sec variable keeps obtaining 283, instead of 17.
Again, I'm not very good with regex, and I'm pretty sure regex is the way to go in this case. Please assist. Thanks.
You don't even need to use regex for this.
$seconds = substr($str, 0, strspn($str, '1234567890'));
The above solution will extract all the digits from the beginning of the string. Doesn't matter if the first non-digit character is "s", a space, or anything else.
But why bother?
You can even just cast $str to an int:
$seconds = (int)$str; // equivalent: intval($str)
See it in action.
Regular expressions are definite overkill for such a simple task. Don't use dynamite to drill holes in the wall.
You could do this like so:
preg_match('/(?<seconds>\d+)s\s*(?<milliseconds>\d+)ms/', $var, $matches);
print_r($matches);
If the string will always be formatted in this manner, you could simply use:
<?php
$timeString = '17s 283ms';
$seconds = substr($timeString, 0, strpos($timeString, 's'));
?>
Well, i guess that you can assume seconds always comes before milliseconds. No need for regexp if the format is consistent. This should do it:
$parts = explode(' ', $str);
$seconds = rtrim($parts[0], 's')
echo $seconds; // 17s
This will split the string by space and take the first part 17s. rtrim is then used to remove 's' and you're left with 17.
(\d+s) \d+ms
is the right regexp. Usage would be something like this:
$str = "17s 283ms";
$groups = array();
preg_match("/(\d+)s \d+ms/", $str, $groups);
Then, your number before ms would be $groups[1].
Related
I have a string with numbers, stored in $numbers:
3,6,86,34,43,52
What's the easiest way to get the last value after the last comma? In this case the number 52 would be the last value, which I would like to store in a variable.
The number can vary in size, so trying:
substr($numbers, -X)
does not help me out I think.
This should work for you:
Just use strrpos() to get the position of the last comma and then use substr() to get the string after the last comma, e.g.
$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);
output:
52
Just explode the string by the separator character and pick the last of the resulting tokens:
<?php
$string = '3,6,86,34,43,52';
$tokens = explode(',', $string);
echo end($tokens);
An alternative would be to use a regular expression:
<?php
$string = '3,6,86,34,43,52';
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);
Personally I have the opinion that efficiency is less important that easy of reading and understanding the code these days. Computation power is cheap, developers are expensive. That is why I would use the first approach, expect when the number of elements in the string gets big.
You can do it like this:
$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);
echo $arr[count($arr)-1];
I'd just explode it to an array, and get the last element:
$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];
A direct, single-function approach would be to trim every upto the last comma.
Code: (Demo)
$numbers = "3,6,86,34,43,52";
echo preg_replace('/.*,/', '', $numbers);
// 52
I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];
I have a string that looks like the following:
Security/Flow_Setup/Steady_State/Verification
I only need the first two levels (e.g. Security/Flow_Setup) Is there an easier way to get this. Currently I explode the string into an array using: '/' as a delimiter and then piece together elements 0 and 1.
This works but I was hoping for a more elegant solution.
Any thoughts?
I don't think you can get too much more elegant/short than this if you only need the first two pieces:
list($var1, $var2) = explode('/', $str);
Regex is totally unnecessary here.
Someone mentioned dirname in the comments, which I thought was a clever and probably appropriate idea, and very short and readable (and gets you the string you need instead of two separate parts like the code above):
$str = 'Security/Flow_Setup/Steady_State/Verification';
echo dirname(dirname($str));
// Output: Security/Flow_Setup
I believe that you do everything ok. You can try it this way if you like:
$str = "Security/Flow_Setup/Steady_State/Verification";
echo substr($str, 0, strpos($str, '/', strpos($str, '/') + 1));
(No arrays involved, should be a little bit faster)
not a typical usage nor a string function, but since your string is effectively a path, maybe this would suffice...
dirname(dirname('Security/Flow_Setup/Steady_State/Verification'));
Here is the shortest and most efficient one-liner I can come up with:
$firstTwoParts = implode('/', array_slice(explode('/', $str, 3), 0, 2));
This could be wrapped into a function that let's you control how many parts you want:
function first_n_parts ($str, $n, $delimiter = '/') {
return ($n = (int) $n) ? implode($delimiter, array_slice(explode($delimiter, $str, $n + 1), 0, $n)) : '';
}
...so you can do:
echo first_n_parts($str, 1); // Security
echo first_n_parts($str, 2); // Security/Flow_Setup
echo first_n_parts($str, 3); // Security/Flow_Setup/Steady_State
this regex should do it
'/^([a-zA-Z]+\/[a-zA-Z]+)?/'
I have many strings that follow the same convention:
this.is.a.sample
this.is.another.sample.of.it
this.too
What i want to do is isolate the last part. So i want "sample", or "it", or "too".
What is the most efficient way for this to happen. Obviously there are many ways to do this, but which way is best that uses the least resources (CPU and RAM).
$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);
echo end($contents); // displays 'it'
I realise this question is from 2012, but the answers here are all inefficient. There are string functions built into PHP to do this, rather than having to traverse the string and turn it into an array, and then pick the last index, which is a lot of work to do something quite simple.
The following code gets the last occurrence of a string within a string:
strrchr($string, '.'); // Last occurrence of '.' within a string
We can use this in conjunction with substr, which essentially chops a string up based on a position.
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'
Note the +1 on the strrchr result; this is because strrchr returns the index of the string within the string (starting at position 0), so the true 'position' is always 1 character on.
http://us3.php.net/strpos
$haystack = "this.is.another.sample.of.it";
$needle = "sample";
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) );
Just do:
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];
echo $last_part; // prints "sparta".
$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function
print_r($result); // whole Array
Will give you
result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
Display any one you want (ex. echo result[5];)
Want to process a set of strings, and trim some ending "myEnding" from the end of each string if it exists.
What is the simplest way to do it?
I know that everything is possible with regexp, but thus seems to be a simple task, and I wonder whether a simpler tool for this exists.
Thanks
Gidi
ima go with preg_replace on this one.
$output = preg_replace('/myEnding$/s', '', $input);
Try this:
$s = "foobarmyEnding";
$toRemove = "myEnding";
$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
$s = substr($s, 0, -$len);
}
ideone
rtrim http://php.net/manual/en/function.rtrim.php
$str = "foobarmyEnding";
$str = rtrim($str, 'myEnding');
// str == "foobar"
ltrim is the same deal for the start of a string http://php.net/manual/en/function.ltrim.php
You could also use str_replace to replace a search term with with an empty string but its slower then rtrim/ltrim if you need to amend the start or end of a string