PHP fix zero-width-space inside string variable - php

I have zipcodes being outputted, coming from user inputted values. Looks like it is outputting zero-width-space \u200b sometimes at the beginning of the strings.
What is the best way to replace these from within php before echoing the variable?

I use this function to trim unicode spaces - this should work in your case too.
function trimUnicode($str) {
return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$str);
}

Ok, seems as though this was coming from the actual string being echo'd by PHP, so I did the following to the string:
$zipcode = trim(utf8_decode($zipcode), '?');
All seems fine now!

Related

Calling a javascript function on a php variable

Javascript:
function capitalizeFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
PHP:
echo "You have chosen a <script>document.write(capitalizeFL(".$race."));</script>";
$race contains a string. What I would like is simply to capitalize the first letter of the php variable $race, using the Javascript function above, and print it on the page.
I could find another way of doing this, but this JS-PHP mixing thing is confusing to me and I'd very much like to figure out WHY this doesn't work.
Look at the generated JavaScript.
document.write(capitalizeFL(value_of_race));
That's an identifier, not a string literal. You need to include quote marks in your generated JS.
Given a string, the json_encode function will output the equivalent JS literal (even if it isn't valid JSON). Use that to convert your PHP variables into JS literals.
$js_race = json_encode($race);
echo "You have chosen a <script>document.write(capitalizeFL($js_race));</script>";
echo "You have chosen a <script>document.write(capitalizeFL('".$race."'));</script>";
You can try above code.
Javascript string must be wrapped by ''.

Is it possible to print php variable withing a variable?

I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.

Understanding 'parse_str' in PHP

I'm a PHP newbie trying to find a way to use parse_str to parse a number of URLs from a database (note: not from the request, they are already stored in a database, don't ask... so _GET won't work)
So I'm trying this:
$parts = parse_url('http://www.jobrapido.se/?w=teknikinformat%C3%B6r&l=malm%C3%B6&r=auto');
parse_str($parts['query'], $query);
return $query['w'];
Please note that here I am just supplying an example URL, in the real application the URL will be passed in as a parameter from the database. And if I do this it works fine. However, I don't understand how to use this function properly, and how to avoid errors.
First of all, here I used "w" as the index to return, because I could clearly see it was in the query. But how do these things work? Is there a set of specific values I can use to get the entire query string? I mean, if I look further, I can see "l" and "r" here as well...
Sure I could extract those too and concatenate the result, but will these value names be arbitrary, or is there a way to know exactly which ones to extract? Of course there's the "q" value, which I originally thought would be the only one I would need, but apparently not. It's not even in the example URL, although I know it's in lots of others.
So how do I do this? Here's what I want:
Extract all parts of the query string that gives me a readable output of the search string part of the URL (so in the above it would be "teknikinformatör Malmö auto". Note that I would need to translate the URL encoding to Swedish characters, any easy way to do that in PHP?)
Handle errors so that if the above doesn't work for some reason, the method should only return an empty string, thus not breaking the code. Because at this point, if I were to use the above with an actual parameter, $url, passed in instead of the example URL, I would get errors, because many of the URLs do not have the "w" parameter, some may be empty fields in the database, some may be malformed, etc. So how can I handle such errors stably, and just return a value if the parsing works, and return empty string otherwise?
There seems to be a very strange problem that occurs that I cannot see during debugging. I put this test code in just to see what is going on:
function getQuery($url)
{
try
{
$parts = parse_url($url);
parse_str($parts['query'], $query);
if (isset($query['q'])) {
/* return $query['q']; */
return '';
}
} catch (Exception $e) {
return '';
}
}
Now, obviously in the real code I would want something like the commented out part to be returned. However, the puzzling thing is this:
With this code, as far as I see, every path should lead to returning an empty string. But this does not work - it gives me a completely empty grid in the result page. No errors or anything during debugging, and objects look fine when I step through them during debugging.
However, if I remove everything from this method except return ''; then it works fine - of course the field in the grid where the query is supposed to be is empty, but all the other fields have all the information as they should. So this was just a test. But how is it possible that code that should only be able to return an empty string does not work, while the one that only returns an empty string and does nothing else does work? I'm thoroughly confused...
The meaning of the query parameters is entirely up to the application that handles the URL, so there is no "right" parameter - it might be w, q, or searchquery. You can heuristically search for the most common variables (=guess), or return an array of all arguments. It depends on what you're trying to achieve.
parse_str already decodes urlencoding. Note that urlencoding is a way to encode bytes, not characters. It depends on what encoding the application expects. Usually (and in this example query), that should be UTF-8 everywhere, so you should be covered on 1.
Test whether the value exists, and if not, return the empty string, like this:
$heuristicFields = array('q', 'w', 'searchquery');
foreach ($heuristicFields as $hf) {
if (isset($query[$hf])) return $query[$hf];
}
return '';
The function returns null if the input is valid, and runs into errors (i.e., displays warning messages) when the URL is obviously invalid. The try...catch block has no effect.
It turned out the problem was with Swedish characters - if I used utf8_encode() on the value before returning it, it worked fine.

Using stripslashes on a database row php

{$row['info']}
How do I use stripslashes() php function on this?
I've tried :
stripslashes({$row['info']}), doesnt work and this: {stripslashes($row['info'])}
Neither work.
Do I have to use a $var first??
Thanks
stripslashes returns the modified string, leaving its argument unchanged. You have to assign the result to a variable:
$var = stripslashes($row['info']);
That said, why are you doing this? You almost certainly shouldn't be. There is no reason to strip slashes on data coming from the database, unless you've double-escaped the slashes when the data was inserted.
Your question is somewhat confusing.
stripslashes() takes parameter and converts backslashed symbols to normal ones. more over, it does not affect the parameter. it returns stripped version.
so $result = stripslashes($source) or $row["info"] in your case.
$var = stripslashes($row['info']);
is more correct. Or in string, use it like this
echo "something".stripslashes($row['info'])." some more thingy";
It almost seems, that you are using heredoc syntax because of your {}. Question, is why? Are you seriously displaying your results like this?:
echo <<<my_results
Info: {$row['info']}
my_results;
Well, since that is cool way to do so then here is your fix:
$row_info = stripslashes($row['info']);
echo <<<my_results
Info: {$row_info}
my_results;
However, I do not recommend that approach. Rather do it like this:
echo 'Info:' . stripslashes($row['info']);
Because {stripslashes($row['info'])} doesn't work indeed and stripslashes({$row['info']}) is an anecdote!

PHP—Empty String Help

The CMS I'm using has a plugin that pulls a series of pages based on how you've tagged those pages. Everything is working fine, but I need to display the number of pages returned after a user sends a query.
The variable that the number of records is stored in is a string. The small script I'm writing tries to check if this string is blank, and if so echo nothing, but if it's not blank echo the number of pages returned.
<?php
if ($count !== ''){
echo "text";
}
?>
However, whenever it's passed when the string is supposed to be empty it treats it as if it is not. I'm not sure what I'm doing wrong or what the string contains that it's not empty.
I found a resource about converting strings to integers but it set it to 0. Thanks for any help.
$count will never be equal to ' ' if you trim it before.
It cannot be equal to ' ' after trim, you should check if it is equal to an empty string and not a string with a white space. (trim deletes white spaces)
trim — Strip whitespace (or other characters) from the beginning and end of a string
http://php.net/manual/en/function.trim.php
trim removes all spaces, so $count == ' ' will always be false if you trimmed first. The easiest change to your code would be to replace the ' ' with ''. Or you could just do this: echo trim($count) === '' ? '' : "text";
trim() is going to remove all white-space characters from the beginning and end of the string. Unless there is content in the middle, you'll likely end up with a completely empty string. If you're testing for this, try checking empty() or is_null().
if (empty($string)) {
echo "String is empty.";
}
I find it's better using built-in functions instead of hard-coding a =='' comparison.
Use var_dump() to check the type and the content of the variable.
Check the manual
Your code seems wrong; you've got "!==", where I'd swear you need to have "!=" (only one equals sign). I'm not sure what "!==" would evaluate to, but I'd bet it's not what you want.
It seems from the comments that your "blank" string is not blank, but instead has something odd in it. Assuming that it's not too odd I'd just try this:
$count = intval($count);
if ($count) {
echo 'text';
}
Though this assumes that the $count actually looks like a number to intval when it's got a number in it -- we may need to take a look at this "string" you're getting back in more detail to figure out what's really in it.
Hopefully you've already taken the advice given by others and looked at the resulting page source after doing a var_dump() -- otherwise I'd guess that $count has XML in it, or something else that won't render well if you dump it to an HTML page and view the page rather than the source...
If nothing else, you could really try brute-forcing it:
$count = intval(preg_replace('/[^\d]/', '', $count));
if ($count) {
echo 'text';
}
...but really it'd be better to work out what this odd plug-in is giving you, and why. Which CMS and plugin is it? Are there some docs available for this thing that's returning $count to you? Do you have the plugin source?

Categories