$string = '540';
if (strlen ($string >= 34)){
print_r((substr($string, 0, 30) . "..."));
} else {
print_r(($string));
}
If $string is longer than 34 characters it should be appended with a "...", otherwise it should just print the string.
I think what's happening is that the interpreter is assuming the string is a number when it does the comparison.
It also has the same hiccup if I change $string to
$string = '540 rocks !'
Why is this?
Should be:
if (strlen($string) >= 34)) {
Not
if ($string >= 34)){
If the test you want to do is on the string length, just change this line:
if ($string >= 34)){
into this:
if (strlen($string) >= 34)){
Related
I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number
assuming $string is your "0101" string, you could just do $m1 = '1'.$string;
My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}
I have a string with, for example, 32 characters. For first, i want to establish that the string have max 32 characters and i want add blank spaces if characters is only, for example, 9.
Example:
ABCDEFGHI ---> 9 characters
I want this:
ABCDEFGHI_______________________ ---> 9 characters + 23 blank spaces added automatically.
The function you are looking for is str_pad.
http://php.net/manual/de/function.str-pad.php
$str = 'ABCDEFGHI';
$longstr = str_pad($str, 32);
The default pad string already is blank spaces.
As your maximum length should be 32 and str_pad won't take any action when the string is longer than 32 characters you might want to shorten it down using substr then:
http://de.php.net/manual/de/function.substr.php
$result = substr($longstr, 0, 32);
This again won't take any action if your string is exactly 32 characters long, so you always end up with a 32 characters string in $result now.
Use str_pad:
str_pad('ABCDEFGHI', 32);
Use str_pad function:
$result = str_pad($input, 32, " ");
you need str_pad
$padded = str_pad($in,32,' ');
You can have left or right padded, tons of options, check them all out here
If the input exceeds 32 chars, no action is taken, but that's an easy check to implement:
if (strlen($padded) > 32)
{
throw new Exception($padded.' is too long');//or some other action
}
If you want to do more customization inside the function you could use this
function fill($input, $length, $filler = ' ')
{
$len = strlen($input);
$diff = $length - $len;
if($diff > 0)
{
for ($i = 0; $i < $diff; $i++)
{
$input = $input . $filler;
}
}
return substr($input, 0, $length);
}
for($i=0;$i<(32-strlen($your_string));$i++)
{
$new_string.=$your_string.' '
}
hope that would be helpful for you
$str = "ABCDEFGHI";
for ($i = 0; $i < 23; $i++) {
$str .= " ";
}
This is what You want?
When saw other comments, then that will be the best solution.
what am I doing wrong here guys?
$string = "string How Long is a Piece of String?";
if $string = <5;
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}
1st, condition are in parenthesis.
2nd, you don't need a ; after a condition.
3rd, less than is simply < not <= unless you want to echo "string is less or equals than 5"
$string = "string How Long is a Piece of String?";
if (strlen($string) < 5)
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}
Others pointed out the syntax errors, to actually compare to the length of the string you need to use the strlen function:
$string = "string How Long is a Piece of String?";
if (strlen($string) < 5)
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}
Type juggling it is called:
http://nl2.php.net/manual/en/language.types.type-juggling.php
$string = "string How Long is a Piece of String?";
if ($string < 5)
string is cast to int, becomes 0
if (0 < 5)
true!
strlen / mbstrlen are possible candidates you're loking for
But that wasn't the question, there are obivously more things wrong with the code :)
may be you're looking for the strlen() function?
missing parentheses around if statement and no need for semi-colon? also less than or equal operator in wrong order. should be like this:
if ($string <=5)
{
echo "string is less than 5";
}
Also note that if that string has multi byte chars it will return a wrong char count, but a byte count.
You'll probably need to know this down the track :) For now, get on top of your syntax.
i wanna get some field values from database and present them on html.
but some of them are longer than the div width so i wanted to chop if of and add 3 dots after them if they are longer than lets say 30 characthers.
windows vs mac os x-> windows vs m...
threads about windows vista -> threads about win...
how can i do that?
If you need to perform this kind of functionality more than once, consider this function:
function truncate($string, $limit, $break = '.', $pad = '...')
{
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit)))
{
if($breakpoint < strlen($string) - 1)
{
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
Usage:
echo truncate($string, 30);
Judging by your examples you don't seem to care about preserving words, so here it is:
if (strlen($str) > 30)
{
echo substr($str, 0, 30) . '...';
}
If you use Smarty, you can use the truncate modifier.
{myLongText|truncate:30:'...':true}
BTW, such kind of function should exist in any decent template engine.
Check out wordwrap(), that should be what you're looking for.
How can I swap around / toggle the case of the characters in a string, for example:
$str = "Hello, My Name is Tom";
After I run the code I get a result like this:
$newstr = "hELLO, mY nAME Is tOM";
Is this even possible?
If your string is ASCII only, you can use XOR:
$str = "Hello, My Name is Tom";
print strtolower($str) ^ strtoupper($str) ^ $str;
Outputs:
hELLO, mY nAME IS tOM
OK I know you've already got an answer, but the somewhat obscure strtr() function is crying out to be used for this ;)
$str = "Hello, My Name is Tom";
echo strtr($str,
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
The quickest way is with a bitmask. No clunky string functions or regex. PHP is a wrapper for C, so we can manipulate bits quite easily if you know your logical function like OR, NOT, AND, XOR, NAND, etc..:
function swapCase($string) {
for ($i = 0; $i < strlen($string); $i++) {
$char = ord($string{$i});
if (($char > 64 && $char < 91) || ($char > 96 && $char < 123)) {
$string{$i} = chr($char ^ 32);
}
}
return $string;
}
This is what changes it:
$string{$i} = chr($char ^ 32);
We take the Nth character in $string and perform an XOR (^) telling the interpreter to take the integer value of $char and swapping the 6th bit (32) from a 1 to 0 or 0 to 1.
All ASCII characters are 32 away from their counterparts (ASCII was an ingenious design because of this. Since 32 is a power of 2 (2^5), it's easy to shift bits. To get the ASCII value of a letter, use the built in PHP function ord():
ord('a') // 65
ord('A') // 97
// 97 - 65 = 32
So you loop through the string using strlen() as the middle part of the for loop, and it will loop exactly the number of times as your string has letters. If the character at position $i is a letter (a-z (65-90) or A-Z (97-122)), it will swap that character for the uppercase or lowercase counterpart using a bitmask.
Here's how the bitmask works:
0100 0001 // 65 (lowercase a)
0010 0000 // 32 (bitmask of 32)
--------- // XOR means: we put a 1 if the bits are different, a 0 if they are same.
0110 0001 // 97 (uppercase A)
We can reverse it:
0110 0001 // 97 (A)
0010 0000 // Bitmask of 32
---------
0100 0001 // 65 (a)
No need for str_replace or preg_replace, we just swap bits to add or subtract 32 from the ASCII value of the character and we swap cases. The 6th bit (6th from the right) determines if the character is uppercase or lowercase. If it's a 0, it's lowercase and 1 if uppercase. Changing the bit from a 0 to a 1 ads 32, getting the uppercase chr() value, and changing from a 1 to a 0 subtracts 32, turning an uppercase letter lowercase.
swapCase('userId'); // USERiD
swapCase('USERiD'); // userId
swapCase('rot13'); // ROT13
We can also have a function that swaps the case on a particular character:
// $i = position in string
function swapCaseAtChar($string, $i) {
$char = ord($string{$i});
if (($char > 64 && $char < 91) || ($char > 96 && $char < 123)) {
$string{$i} = chr($char ^ 32);
return $string;
} else {
return $string;
}
}
echo swapCaseAtChar('iiiiiiii', 0); // Iiiiiiii
echo swapCaseAtChar('userid', 4); // userId
// Numbers are no issue
echo swapCaseAtChar('12345qqq', 7); // 12345qqQ
Very similar in function to the answer by Mark.
preg_replace_callback(
'/[a-z]/i',
function($matches) {
return $matches[0] ^ ' ';
},
$str
)
Explanation by #xtempore:
'a' ^ ' ' returns A. It works because A is 0x41 and a is 0x61 (and likewise for all A-Z), and because a space is 0x20. By xor-ing you are flipping that one bit. In simple terms, you are adding 32 to upper case letters making them lower case and subtracting 32 from lower case letters making them upper case.
You'll need to iterate through the string testing the case of each character, calling strtolower() or strtoupper() as appropriate, adding the modified character to a new string.
I know this question is old - but here's my 2 flavours of a multi-byte implementation.
Multi function version:
(mb_str_split function found here):
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
function mb_is_upper($char) {
return mb_strtolower($char, "UTF-8") != $char;
}
function mb_flip_case($string) {
$characters = mb_str_split($string);
foreach($characters as $key => $character) {
if(mb_is_upper($character))
$character = mb_strtolower($character, 'UTF-8');
else
$character = mb_strtoupper($character, 'UTF-8');
$characters[$key] = $character;
}
return implode('',$characters);
}
Single function version:
function mb_flip_case($string) {
$characters = preg_split('/(?<!^)(?!$)/u', $string );
foreach($characters as $key => $character) {
if(mb_strtolower($character, "UTF-8") != $character)
$character = mb_strtolower($character, 'UTF-8');
else
$character = mb_strtoupper($character, 'UTF-8');
$characters[$key] = $character;
}
return implode('',$characters);
}
Following script supports UTF-8 characters like "ą" etc.
PHP 7.1+
$before = 'aaAAąAŚĆżź';
$after = preg_replace_callback('/./u', function (array $char) {
[$char] = $char;
return $char === ($charLower = mb_strtolower($char))
? mb_strtoupper($char)
: $charLower;
}, $before);
PHP 7.4+
$before = 'aaAAąAŚĆżź';
$after = implode(array_map(function (string $char) {
return $char === ($charLower = mb_strtolower($char))
? mb_strtoupper($char)
: $charLower;
}, mb_str_split($before)));
$before: aaAAąAŚĆżź
$after: AAaaĄaśćŻŹ
I suppose a solution might be to use something like this :
$str = "Hello, My Name is Tom";
$newStr = '';
$length = strlen($str);
for ($i=0 ; $i<$length ; $i++) {
if ($str[$i] >= 'A' && $str[$i] <= 'Z') {
$newStr .= strtolower($str[$i]);
} else if ($str[$i] >= 'a' && $str[$i] <= 'z') {
$newStr .= strtoupper($str[$i]);
} else {
$newStr .= $str[$i];
}
}
echo $newStr;
Which gets you :
hELLO, mY nAME IS tOM
i.e. you :
loop over each character of the original string
if it's between A and Z, you put it to lower case
if it's between a and z, you put it to upper case
else, you keep it as-is
The problem being this will probably not work nicely with special character like accents :-(
And here is a quick proposal that might (or might not) work for some other characters :
$str = "Hello, My Name is Tom";
$newStr = '';
$length = strlen($str);
for ($i=0 ; $i<$length ; $i++) {
if (strtoupper($str[$i]) == $str[$i]) {
// Putting to upper case doesn't change the character
// => it's already in upper case => must be put to lower case
$newStr .= strtolower($str[$i]);
} else {
// Putting to upper changes the character
// => it's in lower case => must be transformed to upper case
$newStr .= strtoupper($str[$i]);
}
}
echo $newStr;
An idea, now, would be to use mb_strtolower and mb_strtoupper : it might help with special characters, and multi-byte encodings...
For a multibyte/unicode-safe solution, I'd probably recommend mutating/toggling the case of each letter based on which capture group contains a letter. This way you don't have to make a multibyte-base check after matching a letter with regex.
Code: (Demo)
$string = 'aaAAąAŚĆżź';
echo preg_replace_callback(
'/(\p{Lu})|(\p{Ll})/u',
function($m) {
return $m[1]
? mb_strtolower($m[1])
: mb_strtoupper($m[2]);
},
$string
);
// AAaaĄaśćŻŹ
See this answer about how to match letters that might be multibyte.