PHP new line every X characters in long characters sequence - php

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/>
?

Related

How to count all the words with special characters

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

How to make so chunk_split doesn't add something at the end of the string

i'm using chunk_split to add a "-" every 4th letter, but it also add one at the end of the string, which i don't want, here's the code:
<?php
function GenerateKey($input)
{
$generated = strtoupper(md5($input).uniqid());
echo chunk_split(substr($generated, -24), 4, "-");
}
?>
Maybe not the most efficient way to generate a serial key, i think it would be better if i used mt_rand, but i think it'll do for now.
So how would i do so it doesn't add a "-" at the end of the string?
Because right now the output looks like this:
89E0-1E2E-1875-3F63-6DA1-1532-
Really appreciate the help i can get
Kind regards,
Jesper
You can remove the trialing - by rtrim. Try this
$str = "89E01E2E18753F636DA11532";
echo rtrim(chunk_split($str,4,"-"), "-");
Output:
89E0-1E2E-1875-3F63-6DA1-1532
You can chop off the - with rtrim():
echo rtrim(chunk_split(substr($generated, -24), 4, "-"), "-");
md5() generates a 32-character string.
uniqid() by default generayes a 13-character string.
You want a 24-character string with delimiting hyphens between every four characters.
You don't need to trim a trailing hyphen if you reconfigure earlier processing.
Generate the random string and prepend 3 arbitrary characters.
Call chunk_split() to apply hyphens.
Cut away the unwanted characters from the front of the string and the trailing hyphen.
Convert the isolated string to uppercase.
Return the value from your function instead of echoing.
Code: (Demo)
function GenerateKey(string $input): string
{
return strtoupper(
substr(
chunk_split(
'...' . md5($input) . uniqid(),
4,
'-'
),
-25,
24
)
);
}
echo GenerateKey('foooobar');

PHP Strip String, Convert to int

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 to split characters with "-" character?

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

Filter out numbers in a string in php

assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
filter_var
flags for the filters
e.g. to get just numbers from the given string
<?php
$a = '!a-b.c3#j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
Edit:
1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].
You can use a regular expression to remove any character that is not a digit:
preg_replace('/\D/', '', $str)
Here the pattern \D describes any character that is not a digit (complement to \d).
Use PHP FILTER functions if you are using PHP 5.2.X, 5.3.x,5.4 . Its highly recommended
$mixed_input = "e3r4t5";
$only_numbers = filter_var($mixed_input, FILTER_SANITIZE_NUMBER_INT);
Please Go through with this link to know more
Replace everything that isn't a number and use that value.
$str = "foo1bar2baz3";
$num = intval(preg_replace("/[^0-9]/", "", $str));
You could use the following function:
function extract_numbers($string) {
preg_match_all('/([\d]+)/', $string, $match);
return $match;
}

Categories