PHP Strip String, Convert to int - php

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.

Related

How to cut only the FIRST character in a string

so I have this situation where I want to cut out the first '1.' out of a string, but not any following '1.'s. I am wondering if this is even possible to do.
So I am converting an it to a string, and I am wondering if there is a way to ONLY cut out the initial '1.' and not any following.
So my script dynamically assigns a number, for example 1, 1.1, 1.2, 2, 3, 3.1 - based on certain criteria. And it was currently adding 1. to the beginning of everything. So 1 would = 1.1, 2.1 would = 1.2.1 so on.
Is there a way to force it to ONLY take out the first and not any following? Here is my source:
$str = (string)$i; $str = $i;
$prepend = $parentPrepend ?
$parentPrepend . '.' . $i
: $str = ltrim($str, '\1');
$i++;
The reason your ltrim code doesn't work is that you are passing in \1 which is not the same as the character 1. \1 refers to the character whose ASCII code is 1 which is not the same as 1 whose ASCII code is actually \49.
Modify your code like this:
ltrim($str, '1');
That should trim all 1s from the left of the string.
However, you should know that the ltrim will remove all matching characters from the left of the string, not just the first one!
If you want only the first, then you should use substr instead, with a test to make sure it is a 1.
if(substr($str, 0, 1) == '1')
$str = substr($str, 1);
And if you want to remove the period too, then simply modify the code to include that (and look at first 2 characters instead of only first character)
if (strlen($str) > 2 && substr($str, 0, 2) == '1.')
$str = substr($str, 2);
use strpos to check if 1. is at the beginning. If it is, then use substr to return the string minus the 1.
$string = '1.1';
if (strpos($string, '1.') === 0) {
$string = substr($string, 2);
}
var_dump($string);
You could also use str_replace with a constraint:
$new_string = str_replace ('1.' , '' , $your_string, 1);

php - Get string before nth dash (-)

I have a string that looks something like this:
abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.
How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.
Try this:
$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';
$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];
echo $part1; //abc-def-ghi-jkl
echo $part2; //mno
See demo
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.
EDIT: Mark M answer is right.
you could try using substr as another possible solution
http://php.net/manual/en/function.substr.php
If I see where you are trying to get with this you could also go onto substr_replace
I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.
You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.
$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
$pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);
Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.

PHP Regexp: drop leading zeros from the end of value after decimal

I am trying to write a regular expression such that if a number have decimal point then the zeros (0) at the end must be removed.
Example:
$value = 234.8076000
After Regexp Replace it should become
234.8076
I am trying the following regexp [0]+$ in preg_replace but the problem is that if the value does not have decimal point and it contain zero at the end then that zero is also removed.
Example:
$value = 2340
It becomes 234 but it should remain 2340
Any idea? Is there any in-built function in php that can do this?
Yes, you really can do it with regex:
$pattern = '/(\.\d*[^0])0+$/';
echo preg_replace($pattern, '$1', '2340'); // 2340
echo preg_replace($pattern, '$1', '2340.0'); // 2340.0
echo preg_replace($pattern, '$1', '2340.07600'); // 2340.076
... but the simplest way is just convert a string value into a float value.
echo (float)'2340'; // 2340
echo (float)'2340.0'; // 2340
echo (float)'2340.07600'; // 2340.076
Echoing floats that are really integer values drops the decimal part apparently - but it seems from your comments it's actually what you want.
You can do it without regexpes:
php > echo ((float)"21.40200")."\n";
21.402
/(\.\d*?)0+$/, works except /\d+\.0{n}/ cases

PHP new line every X characters in long characters sequence

How can I add a new line characters (\n\r) in txt file every 10 characters?
What I have is a long sequence of characters, and I like to create a new line for each 10 characters.
in example, let's say I have that sequence of characters:
FadE4fh73d4F3fab5FnF4fbTKhuS591F60b55hsE
and I like to convert it to that:
FadE4fh73d
4F3fab5FnF
4fbTKhuS59
1F60b55hsE
How can I do that ?
I know that I can use a loop for that, but because the above string is an example and my string that I have to split it is really very very long, just I wander if there is any faster and more easy way to spit my string.
chunk_split($string, 10)
http://php.net/manual/en/function.chunk-split.php for more info
using chunk_split():
$str = chunk_split($str, 10, "\n\r");
or using this regex:
$str = preg_replace("/(.{10})/", "$1\n\r", $str);
And by the way did you mean \r\n (New line in Windows environment) by \n\r?
if so then the third argument for chunk_split() can be omitted.
<?php
$foo = '01234567890123456789012345678901234567890123456789012345678901234567890123456789';
$result = chunk_split ($foo, 10, "\r\n");
echo $result;
?>
As mentioned above, the use of chunk_split() might have unwanted consequences, as the break sequence is always added to the end once again.
You can instead use a combination of str_split() and implode() to first split the string every X characters and then recombine it with a break sequence. By using implode(), the break sequence will not be added to the end, again.
I've build a helper function who does this for me after 75 chars:
function createFold($s, $b = '\\n ') {
$chunks = str_split($s, 75);
return implode($b, $chunks);
}
<b><</b>?<b>php</b><br/>
$body=$row['details'];<br/>
$str = chunk_split($body, 14, "<b><</b><b>br</b><b>/</b>");<br/>
echo $str;<br/>
?

How to get the last char of a string in PHP?

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 />';
}
}

Categories