I need to get the last character of a string.
Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?
substr("testers", -1); // returns "s"
Or, for multibyte strings :
mb_substr("multibyte string…", -1); // returns "…"
substr($string, -1)
Or by direct string access:
$string[strlen($string)-1];
Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.
As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];
From PHP 7.1 you can do this (Accepted rfc for negative string offsets):
<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();
I'll let you guess the output.
Also, I added this to xenonite's performance code with these results:
substr() took 7.0334868431091seconds
array access took 2.3111131191254seconds
Direct string access (negative string offsets) took 1.7971360683441seconds
As of PHP 7.1.0, negative string offsets are also supported.
So, if you keep up with the times, you can access the last character in the string like this:
$str[-1]
DEMO
At the request of a #mickmackusa, I supplement my answer with possible ways of application:
<?php
$str='abcdef';
var_dump($str[-2]); // => string(1) "e"
$str[-3]='.';
var_dump($str); // => string(6) "abc.ef"
var_dump(isset($str[-4])); // => bool(true)
var_dump(isset($str[-10])); // => bool(false)
I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest
substr(trim($string), -1)
EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.
trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:
$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);
I'd advise to go for Gordon's solution as it is more performant than substr():
<?php
$string = 'abcdef';
$repetitions = 10000000;
echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = substr($string, -1);
echo "substr() took " . (microtime(true) - $start) . "seconds\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = $string[strlen($string)-1];
echo "array access took " . (microtime(true) - $start) . "seconds\n";
die();
outputs something like
----------------------------------
10000000 repetitions...
----------------------------------
substr() took 2.0285921096802seconds
array access took 1.7474739551544seconds
As of PHP 8 you can now use str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).
I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.
You can find last character using php many ways like substr() and mb_substr().
If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr
Here i can show you both example:
<?php
echo substr("testers", -1);
echo mb_substr("testers", -1);
?>
LIVE DEMO
A string in different languages including C sharp and PHP is also considered an array of characters.
Knowing that in theory array operations should be faster than string ones you could do,
$foo = "bar";
$lastChar = strlen($foo) -1;
echo $foo[$lastChar];
$firstChar = 0;
echo $foo[$firstChar];
However, standard array functions like
count();
will not work on a string.
Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);
Siemano, get only php files from selected directory:
$dir = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);
foreach($files as $file){
$n = substr($file, -3);
if($n == 'php'){
echo $file.'<br />';
}
}
Related
I have a question about a String i want to count all the characters in the string. Like if i have a string
"Hello world & good morning. The date is 18.05.2016"
You can use explode() to convert string into array and then use count() function to count length of array.
echo count(explode(' ', "Hello world & good morning. The date is 18.05.2016"))
You can try this code.
<?php
$file = "C:\Users\singh\Desktop\Talkative Challenge\base_example.txt";
$document = file_get_contents($file);
$return_array = preg_split("/[\s,]+/",$document);
echo count($return_array);
echo $document;
?>
Hopefully it will be working fine.
The 3rd parameter of str_word_count allows you to set additional characters to be counted as words:
str_word_count($document, 0, '&.0..9');
&.0..9 means it will consider &, ., and range from 0 to 9.
You can count the spaces with substr_count and add one.
echo substr_count($str, " ")+1;
// 9
https://3v4l.org/oJJkt
I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.
I have a question about the PHP trim function.
Consider the following:
$x= '<p>blah</p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This works as expected and prints blah
.
$x= '<p><b>blah</b></p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This prints b>blah</b
I'm not looking for other ways around this.
I do wonder why the trim function shows this behavior (stripping the extra Less-than/Greater-than sign).
Thanks in advance.
trim treats the 2nd argument as a list of characters that can be removed, not as a continuous string. This explains why b remains, but < and > are removed.
This is a default behaviour of trim function. You expect it to trim the exact string, but second parameter is instead a list of characters and any of them will be trimmed if found at each side of the string.
You could use simple RegEx like this:
$x = preg_replace(array('#^<p>#i', '#</p>$#i'), '', $x);
Want to replace specific letters in a string to a full word.
I'm using:
function spec2hex($instr) {
for ($i=0; $i<strlen($instr); $i++) {
$char = substr($instr, $i,1);
if ($char == "a"){
$char = "hello";
}
$convString .= "&#".ord($char).";";
}
return $convString;
}
$myString = "adam";
$convertedString = spec2hex($myString);
echo $convertedString;
but that's returning:
hdhm
How do I do this? By the way, this is to replace punctuation with hex characters.
Thanks all.
Use http://php.net/substr_replace
substr_replace($instr, $word, $i,1);
ord() expects only a SINGLE character. You're passing in hello, so ord is doing its thing only on the h:
php > echo ord('hello');
104
php > echo ord('h');
104
So in effect your output is actually
hdhm
it you want to use your same code just change $convString .= "&#".ord($char).";";
to $convString .= $char;
If you just want to replace the occurrence of a with hello within the string you pass to the function, why not use PHP's str_replace()?
function spec2hex($instr) {
return str_replace("a","hello",$instr);
}
I must assume that you don't want to have hex characters instead of punctuation but html entities. Be aware that str_replace(), when called with arrays, will run over the string for multiple times, thus replacing the ";" in "{" also!
Your posted code is not useful for replacing punctuation.
use strtr() with arrays, it doesn't have the drawback of str_replace().
$aReplacements = array(',' => ',', '.' => '.'); //todo: complete the array
$sText = strtr($sText, $aReplacements);
I have line as 'Delux Room_room'. I want get 'Delux Room' as result. I tried following codes.
Following code give following result.
echo $row.'<br/>';
echo rtrim($row, 'room') .'<br/>';
echo rtrim($row, '_room') .'<br/>';
Result ;-
Delux Room_room
Delux Room_
Delux R
But i want Delux Room. Please help me.
echo rtrim($row, '_room') .'<br/>';
That says "remove characters from the end of the string until you get to one that isn't _, r, o or m." Which obviously isn't what you mean. From the PHP manual:
$charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
You provide a list of characters, not a string you want to remove.
You should probably use substr instead:
echo substr($row, 0, -5); // remove the last 5 characers
Another solution would be to use str_replace to replace unwanted substrings:
echo str_replace('_room', '', $row); // replace "_room" with an empty string
Note that this is less precise than the substr approach.
rtrim's second argument is a set of characters. You'll have to write your own method to remove a specific string instead:
function rtrim_str($str, $trim) {
if (substr($str, -strlen($trim)) == $trim) {
return substr($str, 0, -strlen($trim));
}
return $str; // String not present at end
}
echo rtrim_str($row, '_room');
Alternatively to #lonesomeday's solution, if your last past is of variable length:
$pos = strrpos($row, '_');
echo $substr($row, 0, $pos);
You should use str_replace instead of rtrim, like this:
echo $row.'<br/>';
echo str_replace('room', '', $row) .'<br/>';
echo str_replace('_room', '', $row) .'<br/>';