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/>';
Related
Format of string is as follow
$img = "/images/posts/main.jpg";
$img1 = "/images/posts/john.jpg";
I need to remove /images/posts/ and echo rest of the content.
I tried with strstr, But I found it deals with only character
echo strstr($img, '/images/posts/')
//output => /images/posts/main.jpg
if I use only single character echo strstr($img, '/') Then output is images/posts/.
So I use substr with strstr to get expected result.
echo substr(strstr($img, '/'), 14);
//output => main.jpg
In my case, I am sure it will work constantly with same result because the part images/posts/ remains same and will not change.
But is it really good or fast way to counting and trimming ? Any other fast way to cut /images/posts/ at once ?
Or replace ? is it faster ??
echo str_replace('/images/posts/','',$img);
You can do like this..
Syntax-
str_replace(find, replace, string, count)
For Eg-
str_replace('/images/posts/', '', '/images/posts/main.jpg');
it will print main.jpg
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.
So this is my code: i want get agm from http://example.com?agm=12345 end substr agm to get 12
echo $_GET["agm"] if substr(["agm"], 0, -3);
You have lots of errors in your code.
echo $_GET["agm"] // you should end it with ;
if substr(["agm"], 0, -3);
You should:
Use parenthesis for a criterion, so if(...)
You should use $_GET["agm"] instead of ["agm"]
You can use substr($_GET["agm"],0,2) to take first two characters.
Please refer to manual examples of substr() function.
Do you want to get the value of agm or just the...text? If it's just the text "agm", just write it out as a string...
$str = "agm";
echo $str; // agm
Otherwise, to get the contents of "agm"
$data = $_GET['agm'];
echo $data; // 12345
If that's not what you're after, I really haven't a clue what you're asking.
I want to exclude a specific number like 4800 from a string of numbers like 569048004801.
I'm using php for this and the method preg_match_all some pattern's examples I have tried :
/([^4])([^8])([^0])([^0])/i
/([^4800])/i
If you just want to see if a string contain 4800, you don't need regular expressions :
<?php
$string = '569048004801';
if(strpos($string,'4800') === false){
echo '4800 was not found in the string';
}
else{
echo '4800 was found in the string';
}
More information about strpos in the documentation here
If you mean you simply want to remove 4800 from a string, this is easier with a str_replace:
$str = '569048004801';
$str = str_replace('4800', '', $str);
On the other hand, if you mean you want to know if a particular string of digits contains 4800, this will test that for you:
$str = '569048004801';
if (preg_match_all('/4800/', $str) > 0) {
echo 'String contains 4800.';
} else {
echo 'String does not contain 4800.';
}
/([^4])([^8])([^0])([^0])/i
This actually says, a sequence of four characters that is not "4800". Close.
/([^4800])/i
This actually says, a single character that is not '4', '8', or '0'.
Assuming you mean to capture a number that doesn't contain "4800" in it, I think you might want
/(?!\d*4800)\d+/i
This says, check first that we're not looking at a string of numbers with "4800" somewhere, and provided this is the case, capture the string of numbers. It's called a "negative lookahead assertion".
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 />';
}
}