I generated a serial number with php, the length of this serial number is 16 characters, I want to split this serial number in 4 characters with dash(-) character, like this format xxxx-xxxx-xxxx-xxxx so I wrote this php code:
for ($d=0; $d<=3; $d++){
$tmp .= ($tmp ? "-" : null).substr($serial,$d,4);
}
so this loop will return a serial number with xxxx-xxxx-xxxx-xxxx format,
I want to know is there any better way or function in php?
I searched in internet I found sprintf and number_format but I don't know how can I use this function for this format !
I would use str_split() and implode():
$result = implode( '-', str_split( $serial, 4));
str_split() will break the string into an array, where each element has 4 characters. Then, implode() joins those array pieces together with a dash.
So, if we generate a random $serial with:
$serial = substr(md5(uniqid(rand(), true)), 0, 16);
We would get as output something similar to:
59e6-997f-8446-80a2
Try this :
$str = "xxxxxxxxxxxxxxxx";
echo substr(chunk_split($str, 4, '-'), 0, -1);
Output :
xxxx-xxxx-xxxx-xxxx
Ref: http://www.php.net/manual/en/function.chunk-split.php
str_split, fairly clear...
$hyphenated = implode( '-', str_split( $str, 4));
That is pretty clear, but it seems kind of wasteful to generate an array only to implode it. So I wondered if there was another way...
Faster with preg_replace?
I tried a regex, thinking that would eliminate the need for an intermediate array. After all, why have one problem, when you can have two!
$hyphenated = preg_replace('/(.{4})(?=.)/', '$1-', $str);
That little beastie looks for 4 characters, and as long they are followed by at least one more character, will insert a slash after them.
Trouble is, it turned out to be around 25% slower :(
chunk_split faster and with the same great minty taste!
Prasanth Bendra posted a pretty efficient answer which needs no intermediate array
$hyphenated=substr(chunk_split($str, 4, '-'), 0, -1);
Result! This was at least 25% faster than using str_split measured on a 16 character input string, and just as clear as the str_split method.
You can try str_split() with an implode() such as:
$tmpArray = str_split($tmp, 4);
$serialNumber = implode('-', $tmpArray);
Related
How can I add string to another string after a specific character in PHP? Strings are coming from Database.
$stringDB= "FZE-17-01";
$string_add="RTL";
Final output= FZE-RTL-17-01
I tried functions but I don't want to use a position based function like substr_replace after 4 characters, etc. Any good alternative. $string_add after first -
One of many variants is to use array_splice
$arr = explode('-', $stringDB);
array_splice($arr, 1,0, $string_add);
echo implode('-', $arr);
Hope this could help you.
$stringDB= "FZE-17-01";
$string_add="RTL";
echo $newstr = substr_replace($stringDB, $string_add, 4, 0);
PHP substr_replace
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.
For example, 3 string are the following :
##7##
##563##
##120058##
How can I get those number like this :
echo first number is 7
echo second number is 563
echo third number is 120058
Thank you very much!
$numberAsString = trim($string, '##')
Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.
Of course, regex would also be possible, e.g.:
$didMatch = preg_match('/#+([^#]+)#+/', $string, $matches);
Another possibility still is first extract the remaining part after the initial 2 # and then cast to a number, which seems to be always int in this case:
$number = (int)substr($string, 2);
Still another possibility would be to go by the count of the characters and just use substr like:
$numberAsString = substr($string, 2, -2);
Or you could be creative and use something like explode + implode + array functions:
$numberAsString = array_slice(explode('#', implode('', array_slice(explode('#', $string), 2))), 0, -2);
Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.
In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.
$str = "##563##";
preg_match("|\d+|", $str, $res);
print_r($res);
Just call the filter_var() function it will return the number only.
Whatever the input is, it will only filter the number for you!
filter_var("##120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20
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.
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/>
?