Codeigniter - Character Limiter not working - php

I am echoing a users first name in the header. I have a test first name with many characters.
For eg:
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl"
I'm doing
<?php $first_name = character_limiter($first_name, 10);
echo $firstname;?>
But It's not working. It displays all the characters (asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl) instead of only first 10 characters.
I only want to see teh first 10 characeters. How can I fix this?

Use $firstname as first parameter instead of $first_name (which initially contains nothing) while using character_limiter() function
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl";
$first_name = character_limiter($firstname, 10); // limits $firstname to 10 chars and outputs to $first_name
echo $first_name;
In case that was a typo error while you posted your question, then problem might be with loading of Text Helper in Codeigniter which is required for using this function (CI Text Helper).
You can load Text Helper by specifying it in application/config/autoload.php like this:
$autoload['helper'] = array('text');
Or by loading it specifically in a Controller function like this:
$this->load->helper('text');
UPDATE :
Codeigniter maintains "the integrity of words so the character count may be slightly more or less then what you specify" (ref. CI Text Helper)
Let me explain you this by an example:
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl"; //contains only single word
$first_name = character_limiter($firstname, 10);
Here, CI tries to limit $firstname to 10 chars but since, it encounters a word, it will not try to break it instead it outputs till the end of the word.
Now say you had used,
$firstname = "asdfa sdfasdfj kljldkafjsddfjakdsjflaksjdfl sdjbfsdufb";
This contains three words, so the output will be asdfa sdfasdfj…
Note that here too the limited string contains more than 10 chars but since CI tries to maintain word integrity, it does not break the last word.
If you need to strictly limit input string by character, then, you'll have to use the inbuilt php function substr() as described by Hudixt.

Yes character_limiter() function does not work for longer word to prevent word break and/or distort meaning.
According to codeigniter documentation, it will not try to break long word to maintain its integrity.
As per documentation of
character_limiter
Truncates a string to the number of characters specified. It maintains the integrity of words so the character count may be slightly more or less than what you specify.
but codeigniter does not stops you from limiting exact character, ahead it mentions in note
If you need to truncate to an exact number of characters please see the ellipsize() function below.
so instead of character_limiter() you can use ellipsize() function and it will do exact same.
Hope it help.

Try this,it will fix your issue.
$this->load->helper('text');
$string = "your text here";
$string = character_limiter($string, 10);
echo $string;
Output:your text…

You can also use substr() for this purpose.If you want to add ... after 10 character then take the help of strlen(). Use the code below
<?php
if(strlen($first_name)>10){
$first_name = substr($first_name,0, 10)."...";
}
else{
$first_name = substr($first_name,0, 10);
}
echo $first_name;
?>
Hope this helps you

Related

PHP sql treat special characters

$sql = "INSERT INTO golf (datum, odkud, odjezd ) VALUES ('$datum', '$odkud', '$odjezd')";
if(!mysqli_query($connection,$sql)) {
echo '<p class="error">Záznam nebyl vložen</p>';
} else {
header ("location :/golf");
}
Hello, I am working on my thesis to school. I have this code and my supervisor keeps telling me to "treat special characters". How do I do that? He only saw the code I showed you.
your supervisor just ask you to treat special characters 😊. For that #Pedro’s answer is enough.
$odjezd = mysqli_real_escape_string($connection, $odjezd) // copied from #Pedro’s answer
But if you need more validation,
you can check the format of the date is correct?
$test_arr = explode('/', $POST[‘date’]);
if (count($test_arr) == 3) {
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
} else {
// problem with dates ...
}
} else {
// problem with input ...
}
Likewise you can validate your data according to your required way.
this might be helpful.
User input MUST be sanitized prior to insertion, you'll be opening a door into your server otherwise.
You also need to validate the input. What I normally do, is create a series of regex to validate each field individually, or use one of the available php validate filters.
Remember, you can - and should - do client side validation, which is great to reduce server load, but has 0 value as a security measure because it can be easily faked.
server side validation is the most important as it's your last line of defense.
Don't take user input lightly, tons of servers get hacked due to bad or nonexistent user input sanitization.
To directly answer your question, mysqli_real_escape_string() is your friend to escape special characters, i.e.:
$odjezd = mysqli_real_escape_string($connection, $odjezd)
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
Update:
I have used mysqli_real_escape_string and i am still able to submit
"a{b}c'=%" I would like it to remove spec.characters and just input
abc...how?
Let's assume that $odkud can only contain letters or digits and be 5 chars long only to validate, we can use preg_match() as validator, i.e.:
$id = $_REQUEST['id'];
if (preg_match('/^[a-z\d]{5}$/i', $odkud)) {
# Successful match
} else {
# Match attempt failed
}
Live Regex Example & Explanation
If you just need to remove the special characters use one of the php filters mentioned above or preg_replace, i.e.:
$odkud_filtered = preg_replace('/[^a-z\d]/i', '', $odkud);
# abc
Live Regex Example & Explanation

Strange behaviour from ltrim() with forward slash

I need to remove the beginning part of a URL:
$test = "price/edit.php";
echo ltrim($test,'price/');
shows dit.php
Here is a codepad if you want to fiddle: https://codepad.remoteinterview.io/DominantCalmingBerlinPrice
Any ideas what is going on? I want it to echo edit.php of course.
ltrim removes ALL characters found, consider the following:
$test = 'price/edit.php';
echo ltrim($test, 'dprice/'); // outputs t.php
For this particular scenario, you should probably be using str_replace.
The second argument to ltrim() is a character mask (a list of characters) that should be removed. e is a character that should be removed and so it is removed from edit.
There are many string manipulations that you could use, however since this is a filename/filepath the correct tool is a Filesystem Function, basename():
echo basename($test);
For more information on the filepath check into pathinfo().
Hi I have faced the same problem some time ago and found this solution use it if it suits your need
<?php
$test = "price/edit.php";
echo ltrim(ltrim($test,'price'),'/');
output
edit.php
but i must say you should use basename as all type problem
<?php
$test = "project/price/edit.php";
// echo ltrim(ltrim($test,'price'),'/');// this will give oject/price/edit.phpedit.php
echo basename($test); // and it will generate edit.php

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

GET string from user and process it

I am getting input from user and performing filter on that input text.
Here is the example : CODE
Problem with this is when I take $s statically it works fine, but when I pass it in this way:
http:/mylocalpi/phone_filter.php?text=%27my%20long%20STRING%20with%20124%20mynumberis%208989243three56%20some%2040one34two3473%27
And get
$s = $_GET['text']; //
// $s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533"; this works fine
Then it does not filter last word. can some one tell what can be issue here?
use this
$s = urldecode($_GET['text']);
As far as I can tell, there is a lack of similarity between the string you use in the constant and the one you send through the URL:
Constant:
$s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533";
URL:
$s = "'my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533'";
Because your URL looks like this:
?text=%27…%27
Which is the same as
?text='…'
As you can see you send an extra pair of ' (%27) that surround your string, you don't need them. Try and see what happens if your static version of the string starts and ends with those '. Your URL should look like this:
?text=my%20long%20STRING%20with%20124%20mynumberis%204054545456%208989243three56%20some%20Numbers%20402three1345233nine3%205023one34533
Without any leading or trailing ' (%27).
It's either that, or try to fix your filter to ignore the ' while processing the string. This is most certainly the cause.

How to echo randomly a portion of a string?

i have already succesfully translated some quotes via my translation function __(); and now I want to echo only one of those quotes at random. All quotes are separated in this string with a special character like a |
Sofar I only have this. What code could should go below this tackle my random echo?
$quotes =
__("IF YOU MAKE EVERYTHING BOLD, NOTHING IS BOLD") . "|" .
__("Quality of design is an indicator of credibility") . "|" .
__("People ignore design, that ignores people");
(An important restriction: it is essential that the quotes be exactly closed with __(" and "); sothat they can be checked and translated.) __($variable) doest not work with current clean up scripts that I have bought so these won't work.
You're already calling __() on each of your quotes individually, why not save all the extra translating and do something like:
$quotes = array('quote1', 'quote2', 'quote3');
$index = array_rand($quotes);
echo __($quotes[$index]);
Edit: To satisfy your other requirement, that the call to __() must immediately surround each string, you could do this:
$quotes = array(__('quote1'), __('quote2'), __('quote3'));
$index = array_rand($quotes);
echo $quotes[$index];
The big downside here is that you're now looking up a translation for every string in that array, even though only one is printed, but that's the same situation you had in the "one big string" solution.
Why don't you keep them in an array and translate only what is actually outputted?
$quotes = array(
"IF YOU MAKE EVERYTHING BOLD, NOTHING IS BOLD",
"Quality of design is an indicator of credibility",
"People ignore design, that ignores people",
);
$randomQuote = $quotes[ rand(0, count($quotes)-1)];
echo __($randomQuote);
Why the biscuits are they all in one string, and not an array? Your problem would be immediately solved if this was the case. As stands, split in | and index randomly into the array created to pick a random quote.

Categories