defining the negative start parameter in substr as a variable - php

Is using the following correct for defining the negative start parameter for a substr,
because its the only way i know how to get it to retur the correct result.
$start == (-44);
or
$start == (int) -44;
$pair = substr($str, $start, 4);

the substr call is valid, the only error in your code (posted here) is the == operator.
It should be:
$start = -44;
$pair = substr($str, $start, 4)
Also is the start value -44 the 44th character from start or the end. The above code considers -44 to mean 44th character from end of string.
One more error you could run into is if the length of $str is less than 44.

You can just add a - before an expression (including a variable) to invert its sign:
$pair = substr($str, -$start, 4);
Or
$pair = substr($str, -44, 4);

Related

PHP - strpos - search in all string without offset from X to Y

In strpos function we can define offset - where parser sholud start search our substring in string. I have to create something similar - I have to remove range offsets from string, for exacly:
$string = 'This is my string';
echo strpos($string, 'is my', 0);
and it will be return something position of substring is my in main $string.
But how to tell a PHP script to search in all string (like this script above) but not in position from X to Y? Is it possible?
Note:
I'm using mb_strpos() but I think, a solution will be very similar for both functions.
Thanks.
You need your custom function - that should work for you:
//$X<$Y
funciton getOffset($str, $needle, $X, $Y) {
$str1 = substr($str, 0, $X);
$str2 = substr($str, $Y);
$pos1 = strpos($str1, $needle, 0);
$pos2 = $Y + strpos($str1, 'is my', 0);
return false == $pos1 ? $pos2 : $pos1;
}

PHP: Get nth character from end of string

I'm sure there must be an easy way to get nth character from the end of string.
For example:
$NthChar = get_nth('Hello', 3); // will result in $NthChar='e'
Just do this
$rest = substr("abcdef", -3, 1); // returns 'd'
Like this:
function get_nth($string, $index) {
return substr($string, strlen($string) - $index - 1, 1);
}
from substr examples
// Accessing single characters in a string
// can also be achieved using "square brackets"
thus:
$str = "isogram";
echo $str[-1]; // m
echo $str[-2]; // a
echo $str[-3]; // r
<?php
function get_nth($string, $offset) {
$string = strrev($string); //reverse the string
return $string[$offset];
}
$string = 'Hello';
echo get_nth($string, 3);
As $string[3] will give you the 3rd offset of the string, but you want it backwards, you need to string reverse it.
Edit:
Despite other answers (posted after mine) are using substring, and it can be a one liner, it is hardly readable to have substr($string, -2, 1), then just reverse the string and output the offset.
substr($string, -3);//returns 3rd char from the end of the string

How to get everything after a certain character?

I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:
"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"
How can I go about doing something like this?
The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
strtok is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
Here is the method by using explode:
$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string
or:
$text = end((explode('_', '233718_This_is_a_string', 2)));
By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.
Here is another one-liner by using strpos (as suggested by #flu):
$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
I use strrchr(). For instance to find the extension of a file I use this function:
$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns "jpg"
Another simple way, using strchr() or strstr():
$str = '233718_This_is_a_string';
echo ltrim(strstr($str, '_'), '_'); // This_is_a_string
In your case maybe ltrim() alone will suffice:
echo ltrim($str, '0..9_'); // This_is_a_string
But only if the right part of the string (after _) does not start with numbers, otherwise it will also be trimmed.
if anyone needs to extract the first part of the string then can try,
Query:
$s = "This_is_a_string_233718";
$text = $s."_".substr($s, 0, strrpos($s, "_"));
Output:
This_is_a_string
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
If you want to get everything after certain characters and if those characters are located at the beginning of the string, you can use an easier solution like this:
$value = substr( '123_String', strlen( '123_' ) );
echo $value; // String
Use this line to return the string after the symbol or return the original string if the character does not occur:
$newString = substr($string, (strrpos($string, '_') ?: -1) +1);

PHP count, add colons every 2 characters

I have this string
1010081-COP-8-27-20110616214459
I need to count the last 6 characters starting from the end of this string (because it could may be long starting from the begin)
Then I need to add colons after every 2 characters.
So after counting 6 characters from the end it will be
214459
After having added the colons it will look like:
21:44:59
Can you help me achieving it?
I do not really know where to start!
Thank you
You can do this with substr, str_split and implode
The code is done on multiple lines for clarity, but can easily be done in a chain on one line:
$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array. Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string. Each element separated by the given separator.
$result = implode(':', $chunks);
echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);
It looks to me though like that string has a particular format which you should parse into data. Something like:
sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);
If you just want the time:
$time = rtrim(chunk_split(substr($s,-6),2,':'),':');
$final = "1010081-COP-8-27-20110616214459";
$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);
echo "$a:$b:$c";

Help on parsing formatted string

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].

Categories