How to adjusting string length - php

I am trying to limit the characters of a string. Additionally, if the string is less than the required characters, I want to add padding to it.
function create_string($string, $length) {
$str_len = strlen($string);
if($str_len > $length) {
//if string is greater than max length, then strip it
$str = substr($string, 0, $length);
} else {
//if string is less than the required length, pad it with what it needs to be the length
$remaining = $length-$str_len;
$str = str_pad($string, $remaining);
}
return $str;
}
My input is
"Nik's Auto Salon"
which is 16 characters. The second parameter is 40.
However, This string is returned
"Nik's Auto Salon "
which has only eight characters of padding added onto it. That doesn't seem right.
I also tried this string:
Gold Package Mobile Car Detail
With this input, it returns a string with NO padding added onto it. When that phrase is shorter than the required 45 length I put in the second parameter place.
How can I make this function work according to my specifications?

str_pad doesn't add spaces equal to its second parameter, it pads the string TO the length given in the second parameter. This isn't very clear even in the documentation.
Try this instead (and take out the line where you calculate $remaining):
$str = str_pad($string, $length);

Related

generate a meaningful random string using php

I would like to generate a random string with meaningful word
function randString($length, $charset='abcdefghijklmnopqrstuvwxyz'){
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
I have used this function but it generate random which has not any meaning in dictionary.
Have you any idea or is it not possible.
Please let me know if you have any idea according or have better solution regarding.
Thanks in advance.
Try this for a random alphanumeric string
function get_random_string($valid_chars, $length) {
$random_string = '';
//Count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
//Repeat the steps until we've created a string of the right length
for($i=0;$i<$length;$i++) {
//Pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
//Take the random character out of the string of valid chars
//Subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
As Mark Baker writes in the comments, "meaningful" and "random" are hard to bring together.
However, if you want to show a real word, from a given language, without someone being able to guess in advance what that word will be, you would do it as follows (in pseudocode, don't have time to write it out as PHP):
read list of unique words in language into wordList
generate random integer i, <= length of wordList
return word at position i in wordList
Consider using a password dictionary as the source of your wordlist.
Get a list of words from ASPELL or http://sourceforge.net/projects/wordlist/, importing them into a db table and randomly select one by php :)
Sample query:
SELECT word FROM dictionary order by RAND() LIMIT 1

Get int position from string PHP

I receive data from a PUSH service. This data is compressed with gzcompress(). At the very Beginning of the data, it contains an int which is the length of the data contained. This is done after the gzcompress(); So a sample data would be:
187xœËHÍÉÉ,
Which is produced by
echo '187'.gzcompress('Hello');
Now, I don't know the length of the int, it could be 1 digit it could be 10 digits. I also don't know the first character to find the position of the beginning of a string.
Any ideas on how to retrieve/subtract the int?
$length_value=???
$string_value=???
Assuming that the compressed data would NEVER start with a digit, then a regex would be easiest:
$string = '187xœËHÍÉÉ,';
preg_match('/^(\d+)/', $string, $matches);
$number = $matches[0];
$compressed_data = substr($string, 0, strlen($number));
If the compressed data DOES start with a digit, then you're going to end up with corrupt data - you'll have absolutely no way of differentiating where the 'length' value stops and the compressed data starts, e.g.
$compressed = '123foo';
$length = '6';
$your_string = '6123foo';
Ok - is that a string of length 61, with compressed data 23foo? or 612 + 3foo?
You could use preg_match() to catch the integer at the start of the string.
http://php.net/manual/en/function.preg-match.php
You could do:
$contents = "187xœËHÍÉÉ,";
$length = (int)$contents;
$startingPosition = strlen((string)$length);
$original = gzuncompress(substr($contents, $startingPosition), $length);
But I feel this may fail if the first compressed byte is a number.

PHP conditional loop - string length

I am sorry if this is a very stupid question, or an obvious newbie mistake - but I as basic as this is , I hardly never used the do - while loop before (I know - I can not comprehend it myself ! How is it possible that I managed to avoid it all those years ??)
so :
I want to select a number of words from the begining of a text paragraph.
I used the following code :
$no_of_char = 70;
$string = $content;
$string = strip_tags(stripslashes($string)); // convert to plaintext
$string = substr($string, 0, strpos(wordwrap($string, $no_of_char), "\n"));
Which Kind of works, but the problem is that sometimes it gives EMPTY results.
I would think that is because the paragraph contains spaces, empty lines , and / or carriage returns...
So I am trying to make a loop condition that will continue to try until the length of the string is at least X characters ..
$no_of_char = 70; // approximation - how many characters we want
$string = $content;
do {
$string = strip_tags(stripslashes($string)); // plaintext
$string = substr($string, 0, strpos(wordwrap($string, $no_of_char), "\n")); // do not crop words
}
while (strlen($string) > 8); // this would be X - and I am guessing here is my problem
Well - obviously it does not work (otherwise this question would not be ) - and now it ALWAYS produces nothing .(empty string)
Try using str_word_count:
$words = str_word_count($string, 2);
2 - returns an associative array, where the key is the numeric
position of the word inside the string and the value is the actual
word itself
Then use array_slice:
$total_words = 70;
$selected_words = array_slice($words, 0, $total_words);
The most likely problem you have is that the string has blank lines at the start. You can easily get rid of them with ltrim(). Then use your original code to get the first actual newline.
The reason your loop didn't work is because you told it to reject anything that was longer than 8 characters.

Random String Generator (PHP)

I am trying write a PHP function that returns a random string of a given length. I wrote this:
<?
function generate_string($lenght) {
$ret = "";
for ($i = 0; $i < $lenght; $i++) {
$ret .= chr(mt_rand(32,126));
}
return $ret;
}
echo generate_string(150);
?>
The above function generates a random string, but the length of the string is not constant, ie: one time it is 30 characters, the other is 60 (obviously I call it with the same length as input every time). I've searched other examples of random string generators, but they all use a base string to pick letters. I am wondering why this method is not working properly.
Thanks!
Educated guess: you attempt to display your plain text string as HTML. The browser, after being told it's HTML, handles it as such. As soon as a < character is generated, the following characters are rendered as an (unknown) HTML tag and are not displayed as HTML standards mandate.
Fix:
echo htmlspecialchars(generate_string(150));
This is the conclusion i reached after testing it a while : Your functions works correctly. It depends on what you do with the randomly generated string. If you are simply echo-ing it, then it might generate somthing like <ck1ask which will be treated like a tag. Try eliminating certain characters from being concatenated to the string.
This function will work to generate a random string in PHP
function getRandomString($maxlength=12, $isSpecialChar=false)
{
$randomString=null;
//initalise the string include lower case, upper case and numbers
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//if required special character to include, please set $isSpecialchar= 1 or true
if ($isSpecialChar) $charSet .= "~##$%^*()_±={}|][";
//loop for get specify length character with random characters
for ($i=0; $i<$maxlength; $i++) $randomString .= $charSet[(mt_rand(0, (strlen($charSet)-1)))];
//return the random string
return $randomString;
}
//call the function set value you required to string length default:12
$random8char=getRandomString(8);
echo $random8char;
Source: Generate random string in php

Measure string size in Bytes in php

I am doing a real estate feed for a portal and it is telling me the max length of a string should be 20,000 bytes (20kb), but I have never run across this before.
How can I measure byte size of a varchar string. So I can then do a while loop to trim it down.
You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings.
For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:
<?php
$string = 'Cién cañones por banda';
echo mb_strlen($string, '8bit');
?>
You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php
For trim the string by byte length without split in middle of a multibyte character you can use:
mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
Do you mean byte size or string length?
Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.
PHP's strlen() function returns the number of ASCII characters.
strlen('borsc') -> 5 (bytes)
strlen('boršč') -> 7 (bytes)
$limit_in_kBytes = 20000;
$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
// here you can handle (0 - n) parts of string
$pointer++;
}
$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string
.. or you can use a function like this:
function parseStrToArr($string, $limit_in_kBytes){
$ret = array();
$pointer = 0;
while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
$ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
$pointer++;
}
$ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
return $ret;
}
$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);
Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:
$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);

Categories