PHP: Get nth character from end of string - php

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

Related

How can I display all the characters after 20 characters in a string using PHP?

For example, in the string given below:
$string = "adadadadadadadadaadadadadadadadadadadadadadadadadadadadadadadadadadadadadaddadadadadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaafewgewrehrejrejreerj";
I would like the output to consist of all the characters except the first 20.
How do I achieve this?
Here is the code:
$string = "adadadadadadadadaadadadadadadadadadadadadadadadadadadadadadadadadadadadadaddadadadadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaafewgewrehrejrejreerj";
echo substr($string, 20)
And check output.
Here is the code,
echo substr($string, 20);
Documentation link of substr which states Return part of a string depends on your requirement.
If you need the right part of the string after the 20th character you could use substr
$string = "adadadadadadadadaadadadadadadadadadadadadadadadadadadadadadadadadadadadadaddadadadadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaafewgewrehrejrejreerj";
$rest = substr($string, 20, -1);
see this for ref http://php.net/manual/en/function.substr.php
You can use the substr($string, $start)
You can see the manual here http://php.net/manual/en/function.substr.php
if you have to only print string then you can direct echo / print .
echo "your string";
$twentieth_char = substr($string, 19, 1);

Place space or dash between number

I have number 123456789.
I want to place - between two number till my given number count would not be end.
$nubmer = 1234567890.
output will be 12-34-56-78-90
function splitNum($num) {
return implode("-", str_split($num, 2));
}
echo splitNum("1234567890") //output: 12-34-56-78-90
Check the Manual for information on str_split and join
<?php
$number = 1234567890;
$split = str_split($number,2);
echo join('-',$split);
?>
You can use simple one liner wordwrap - Wraps a string to a given number of characters:
<?php
$number = 1234567890;
echo wordwrap($number, 2, '-',true);
output:
12-34-56-78-90
You need to convert the number to string and split it into equal part of 2. then implode them. Conversion is not mandatory but good for perfect result.
$nubmer = "1234567890"; //OR $nubmer = 1234567890;
$arr = str_split($nubmer, 2);
echo implode("-", $arr);//12-34-56-78-90
"One-line" solution using chunk_split and trim functions:
$nubmer = "1234567890";
$splitted = trim(chunk_split($nubmer, 2, "-"), "-"); // contains "12-34-56-78-90"
http://php.net/manual/en/function.chunk-split.php

str replace - replace the x-value

Assuming I have a string
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
there are three 1024, I want to replace the third with JJJJ, like this :
output :
0000,1023,1024,1025,1024,1023,1027,1025,JJJJ,1025,0000
how to make str_replace can do it
thanks for the help
As your question asks, you want to use str_replace to do this. It's probably not the best option, but here's what you do using that function. Assuming you have no other instances of "JJJJ" throughout the string, you could do this:
$str = "0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
$str = str_replace('1024','JJJJ',$str,3)
$str = str_replace('JJJJ','1024',$str,2);
Here is what I would do and it should work regardless of values in $str:
function replace_str($str,$search,$replace,$num) {
$pieces = explode(',',$str);
$counter = 0;
foreach($pieces as $key=>$val) {
if($val == $search) {
$counter++;
if($counter == $num) {
$pieces[$key] = $replace;
}
}
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_str($str, '1024', 'JJJJ', 3);
I think this is what you are asking in your comment:
function replace_element($str,$search,$replace,$num) {
$num = $num - 1;
$pieces = explode(',',$str);
if($pieces[$num] == $search) {
$pieces[$num] = $replace;
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_element($str,'1024','JJJJ',9);
strpos has an offset, detailed here: http://php.net/manual/en/function.strrpos.php
So you want to do the following:
1) strpos with 1024, keep the offset
2) strpos with 1024 starting at offset+1, keep newoffset
3) strpos with 1024 starting at newoffset+1, keep thirdoffset
4) finally, we can use substr to do the replacement - get the string leading up to the third instance of 1024, concatenate it to what you want to replace it with, then get the substr of the rest of the string afterwards and concatenate it to that. http://www.php.net/manual/en/function.substr.php
You can either use strpos() three times to get the position of the third 1024 in your string and then replace it, or you could write a regex to use with preg_replace() that matches the third 1024.
if you want to find the last occurence of your string you can used strrpos
Do it like this:
$newstring = substr_replace($str,'JJJJ', strrpos($str, '1024'), strlen('1024') );
See working demo
Here's a solution with less calls to one and the same function and without having to explode, iterate over the array and implode again.
// replace the first three occurrences
$replaced = str_replace('1024', 'JJJJ', $str, 3);
// now replace the firs two, which you wanted to keep
$final = str_replace('JJJJ', '1024', $replaced, 2);

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);

defining the negative start parameter in substr as a variable

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);

Categories