I'm programming a function to build an URL, here it is :
public static function requestContent($p_lParameters)
{
$sParameters = "?key=TEST&format=json&jsoncallback=none";
foreach($p_lParameters as $sParameterName => $sParameterValue)
{
$sParameters .= "&$sParameterName=$sParameterValue";
}
echo "<span style='font-size: 16px;'>URL : http://api.oodle.com/api/v2/listings" . $sParameters . "</span><br />";
$aXMLData = file_get_contents("http://api.oodle.com/api/v2/listings" . $sParameters);
return json_decode($aXMLData,true);
}
And I am calling this function with this array list :
print_r() result : Array ( [region] => canada [category] => housing/sale/home )
But this is very strange I get an unexpected character (note the special character none**®**ion) :
http://api.oodle.com/api/v2/listings?key=TEST&format=json&jsoncallback=none®ion=canada&category=housing/sale/home
For information I use this header :
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<?php header('Content-Type: text/html;charset=UTF-8'); ?>
EDIT :
$sRequest = "http://api.oodle.com/api/v2/listings?key=TEST&format=json&jsoncallback=none®ion=canada&category=housing/sale/home";
echo "<span style='font-size: 16px;'>URL : " . $sRequest . "</span><br />";
return the exact URL with problem :
http://api.oodle.com/api/v2/listings?key=TEST&format=json&jsoncallback=none®ion=canada&category=housing/sale/home
here is the solution and this time it will work
$sParameters .= "&$sParameterName=$sParameterValue";
$sParameters = htmlentities($sParameters);
It converts all the charset into html code.. totally forgot about this even when I regualarly use it in user input...
Well, first you build a string
$sParameters = "?key=TEST&format=json&jsoncallback=none";
And then you're appending to that. So it will concatenate.
Now, the last part of a string might be & and your parameter is region.
Somehow that gets converted to the html ASCII code ® which causes the registered symbol to appear.
Related
I have a php variable containing some special characters, inside a Codeigniter 3 controller:
page_url = 'search=' . $expression . '&page';
In a template, I use this variable:
In the in the browser I see the characters mentioned above in this form:
posts/search?search%3Dharum%26page=2
The = sign turns to %3D, "&" to %26.
I tried page_url = urldecode($page_url); but it does not work.
How do I keep the original characters?
Please use utf8 decode and try again
echo utf8_decode(urldecode("search%3Dharum%26page=2"));
Try this decode function.
function decode($url)
{
$special = array(
'%21' => '!', '\\' => '%5C', // so on you need to define.
);
foreach($special as $key => $value)
{
$result = str_replace($key, $value, $url);
}
return $result;
}
echo decode("search=%21");
Your problem is not that easy to reproduce. The following rextester demo produces the text in the form you request, using basically your code: http://rextester.com/YTY13099
<?php
$page=2;
$expression='harum';
$page_url = 'posts/search?search=' . $expression . '&page=' . $page;
?>
resulting in
Link
Could it be that the problem is caused by that fact that the script is part of a codeigniter controller? I do not know anything about codeigniter but I can image that further processing takes place there.
I am using the following function in PHP to trim some unwanted characters.
$inputString = "आनन्द मठ";
trim(html_entity_decode($inputString), " \t\n\r\0\x0B\xC2\xA0");
The above code is working fine for all cases but in one input string (आनन्द मठ) it is converting it to आनन्द म�. It has a unwanted �. Also happening for परेटो- श्रेष्ठ converted to परेटो- श्रेष्�.
trim()
This function use iso-8859 encoding.
you must use UTF8 (Unicode) function. Try this function
function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
{
$both_ends = $ltrim && $rtrim;
$char_class_inner = preg_replace(
array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
array( '\\\\\\0', '\\' ),
$charlist
);
$work_horse = '[' . $char_class_inner . ']+';
$ltrim && $left_pattern = '^' . $work_horse;
$rtrim && $right_pattern = $work_horse . '$';
if($both_ends)
{
$pattern_middle = $left_pattern . '|' . $right_pattern;
}
elseif($ltrim)
{
$pattern_middle = $left_pattern;
}
else
{
$pattern_middle = $right_pattern;
}
return preg_replace("/$pattern_middle/usSD", '', $string) );
}
Add http header in your php like
header("Content-Type: text/html; charset=ISO-8859-1");
or put the encoding in a meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
I have been trying to run through a string and find and replace URLs with a link, here what I have come up so far, and it does seem to work for the most part quite well, however there are a few things I'd like to polish. Also it might not be the best performing way of doing that.
I have read many threads on this here on SO, and although it helped a great deal, I still need to tie up the loose ends on it.
I am running through the string two times. The first time I am replacing bbtags with html tags; and the second time I am running through the string and replacing text urls with links:
$body_str = preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/i', '\2', $body_str);
$body_str = preg_replace_callback(
'!(?:^|[^"\'])(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?!',
function ($matches) {
return strpos(trim($matches[0]), 'thisone.com') == FALSE ?
'' . ltrim($matches[0], "\t\n\r\0\x0B.,#?^=%&:/~\+#'") . '' :
'' . ltrim($matches[0], "\t\n\r\0\x0B.,#?^=%&:/~\+#'") . '';
},
$body_str
);
So far the few problems I am finding with this is it tends to pick up the character immediatelly before 'http' etc e.g. a space/comma/colon etc, which broke the links. Thus I used the preg_replace_callback to work around that and trim some unwanted characters that would break the link.
The other problem is that to avoid breaking links by matching urls, which are already in A-tags I am currently excluding urls starting with a quote,double-quote, and I'd rather use href='|href=" for exclusion.
Any tips and advice will be much appreciated
First i allowed myself to refactor a bit your code to make it easier to read and modify :
function urltrim($str) {
return ltrim($str, " \t\n\r\0\x0B.,#?^=%&:/~\+#'");
}
function addlink($str,$nofollow=true) {
return '<a href="' . urltrim($str) . '"'.($nofollow ? ' rel="nofollow" target="_blank"' : '').'>' . urltrim($str) . '</a>';
}
function checksite($str) {
return strpos(trim($str), 'thisone.com') == FALSE ? addlink($str) : addlink($str,false);
}
$body_str = preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/i', '\2', $body_str);
$body_str = preg_replace_callback(
'!(?:^|[^"\'])(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#])?!',
function ($matches) {
return checksite($matches[0]);
},
$body_str
);
After that i changed the way you handle links :
I considered that the URL is a word (= all characters until you find a space or \n or \t (=\s))
I changed the matching method to match the existence of href= in the front of the string
if it exists then I don't do anything, it's already a link
if no href= is present, then i replace the link
So the urltrim method is not useful anymore since I don't eat up the first char before http
And of course, i use urlencode to encode the url and avoid html injection
function urltrim($str) {
return $str;
}
function addlink($str,$nofollow=true) {
$url = preg_replace("#(https?)%3A%2F%2F#","$1://",urlencode(urltrim($str)));
return '<a href="' . $url . '"'.($nofollow ? ' rel="nofollow" target="_blank"' : '').'>' . urltrim($str) . '</a>';
}
function checksite($str) {
return strpos(trim($str), 'thisone.com') == FALSE ? addlink($str) : addlink($str,false);
}
$body_str = preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/i', '\2', $body_str);
$body_str = preg_replace_callback(
'!(|href=)(["\']?)(https?://[^\s]+)!',
function ($matches) {
if ($matches[1]) {
# If href= is present, dont do anything, return the original string
return $matches[0];
} else {
# add the previous char (" or ') and the link
return $matches[2].checksite($matches[3]);
}
},
$body_str
);
I hope this can help you in your project.
Tell us if it helped.
Bye.
I'm trying to build a placeholder meta description for a page, in case the user hasn't included a description in the CMS.
I have started with the following code, but of course it fails if any of the other variables are empty too, such as $phone, $location['zip'] and so on.
<?php
if (!empty($description)) {
echo '<meta name="description" content="' .$description . '">';
}
else {
// Should return: Apple is a business located in Palo Alto, 95014. Call 408.996.1010...
$description = $name . ' is a ' . strtolower($category) . ' located in ' . $location['city'] . ', ';
$description .= $location['zip'] . '. Call ' . $phone . ' for more details today.';
echo '<meta name="description" content="' . $description . '">';
} ?>
What's the most efficient way to build a description in this way? Currently I can only think of nested if statements which sounds messy and I'm sure there must be a clean way to do this.
add a function to check if value is set?
i.e.
function checkData($data) {
if(!empty($data)) {
return $data;
} else {
return '';
}
}
$description = checkData($name) . ' is a ' . strtolower(checkData($category)) . ' located in ' . checkData($location['city']) . ', ';
As the description is something that varies based on the input, put it into a function or class of it's own to encapsulate it:
/**
* build a description based on various input variables
* #return string
*/
function build_description($description, $name, $category, array location, $phone) {
// build the description as you see fit.
}
$description = build_description(compact('description', 'name', 'category'));
$metaDescription = sprintf('<meta name="description" content="%s"', htmlspecialchars($description));
that done, the concrete implementation within build_description can contain a lot of complex statements, while the rest of the program can deal with it as if it is something simple.
However, this does not answer how you could code it inside that function. But as the data of the output of that function heavily depends on the input of that function, you can only deal with all aspects the arguments do impose.
The other variables defined shouldn't be string but part of an object such as... Description.
In this case, it would be easier, calling a Description->isEmpty() that returns true if one of those variables are empty.
If you are stuck with this configuration, you still can make an array:
$myArray=array($name, $category,...);
and check in a loop or maybe the return of in_array('',$myArray)
$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;"
echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol so something thats more readable and elegant to use?
Thanks
For linebreaks, PHP as "\n" (see double quote strings) and PHP_EOL.
Here, you are using <br />, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br() function, which inserts <br> before \n.
I have defined this:
if (PHP_SAPI === 'cli')
{
define( "LNBR", PHP_EOL);
}
else
{
define( "LNBR", "<BR/>");
}
After this use LNBR wherever I want to use \n.
in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n"
but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..
so you can use it using define
define ("EOL","<br>");
then you can call it
I ended up writing a function that has worked for me well so far:
// pretty print data
function out($data, $label = NULL) {
$CLI = (php_sapi_name() === 'cli') ? 'cli' : '';
$gettype = gettype($data);
if (isset($label)) {
if ($CLI) { $label = $label . ': '; }
else { $label = '<b>'.$label.'</b>: '; }
}
if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
if ($CLI) { echo $label . $data . "\n"; }
else { echo $label . $data . "<br/>"; }
}
else {
if ($CLI) { echo $label . print_r($data,1) . "\n"; }
else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
}
}
// Usage
out('Hello world!');
$var = 'Hello Stackoverflow!';
out($var, 'Label');
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:<br />
$myoutput = "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput = str_replace(".|..","<br />",$myoutput);<br />
or
how about:<br />
$myoutput = "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput = str_replace("E(*)3","<br />",$myoutput);<br />
I call the first method "middle finger style" and the second "goatse style".
Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.
Well, as with any language there are several ways to do it.
As previous answerers have mentioned, "<br/>" is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:
// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";
If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:
// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);
However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.
\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.
str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.