What's the standard way to generate a url like stuff? - php

$arr = array('key1'=>'val1','key2'=>'val2');
$str = '';
foreach($arr as $k=>$v)
{
$str .= '&' . $k . '=' . urlencode($v);
}
echo substr($str,1);
Or
$arr = array('key1'=>'val1','key2'=>'val2');
$str = '';
foreach($arr as $k=>$v)
{
$str .= '&' . urlencode($k) . '=' . urlencode($v);
}
echo substr($str,1);
Does the $k need to be urlencoded?

Yes;
If you use PHP5 i Guess the http_build_query would be just what you need ;)
http://nl2.php.net/manual/en/function.http-build-query.php

Related

Adding custom masks to phone numbers

So i'm creating a simple function to mask phone numbers. My phone numbers have a 9 digits and i want preg_replace them with a given mask like 2-2-2-1-2 or 3-2-2-2 and etc.
I tried this:
$mask = explode('-', '3-2-2-2');
$pattern = '';
$replace = '';
foreach ($mask as $key => $value) {
if ($key == 0) {
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$replace = '$' . ++$key . '-';
continue;
}
if ($key == count($mask) - 1) {
$pattern .= '?(\d{' . $value . '})/';
$replace .= '$' . ++$key;
break;
}
$pattern .= '?(\d{' . $value . '})[- ]';
$replace .= '$' . ++$key . '-';
}
return preg_replace($pattern, $replace, '902000810');
and the result is 902-00-08-10. Sometimes getting error preg_replace(): No ending delimiter '/' found. How can i refactor this to not getting errors?
Assuming:
$num = '902000810';
$mask = explode('-', '3-2-2-2');
There're other ways than using regex to format a phone number from the mask.
using formatted strings:
$maskPH = array_map(fn($i) => "%{$i}s", $mask);
$formatI = implode('', $maskPH);
$formatO = implode('-', $maskPH);
$result = vsprintf($formatO, sscanf($num, $formatI));
using unpack:
$format = array_reduce($mask, function ($c, $i) {
static $j = 0;
return "{$c}A{$i}_" . $j++ . "/";
});
$result = implode('-', unpack($format, $num));
preg_replace(): No ending delimiter '/' found
means that your pattern does not terminate with a / as last character.
But all three patterns lack proper formatting:
You should modify them accordingly.
From:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$pattern .= '?(\d{' . $value . '})/';
$pattern .= '?(\d{' . $value . '})[- ]';
To:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]/';
$pattern .= '/?(\d{' . $value . '})/';
$pattern .= '/?(\d{' . $value . '})[- ]/';

PHP line break inside of cell remove qoute

This is my PHP
$val = "";
foreach($data as $v){
$val .= '"' . $v . "\n" . '"';
}
The result is
//this is inside of cell
sample
"sample
"sample
This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.
EDIT
This is the result of my code
This is what I want
Just Remove some part of your code, you will get solution:
$val = "";
foreach($data as $v){
$val .= $v . "\n";
}
Just try (Maintaining line break in excel):
$val = "";
foreach($data as $v){
$val .= $v . "<br style='mso-data-placement:same-cell;' />";
}
Somthing like this should do the trick
$i = 0
foreach($data as $v){
$val .= '"' . $v . "\n" . (count($data) !== $i) ? '"' : '';
$i++;
}
I think you can use the php function trim like this:
$val = "";
foreach($data as $v){
if( ''==$val) {
$val .= trim('"' . $v . "\n" . '"','"');
}else{
$val .= '"' . $v . "\n" . '"','"';
}
}
$val .= '"' . $v . "</br>" . '"';
$val=str_replace('"','',$val);
I think this is what you are looking for inside your loop. It will remove every double quote.
Well there you go :
$data = ['sample','sample','sample'];
$val = "";
foreach($data as $v){
$val .= $v . "\n" ;
}
Then you simply use fputcsv() like this :
$fp = fopen('file.csv', 'w');
fputcsv($fp, [$val]);
And you get the result you want :
The answer to my question is
$val = "";
foreach($data as $v){
$val .= $v . "\n";
}
$val = '"'. $val .'"';
I need to add the '"' outside of the loop.

Convert php arrays with the new syntax

I looking for a way (regex, snippet ,plugin etc) to convert the old arrays with the new php syntax with sublimeText.
// Old synthax
$var = array(
'foo' => 'bar'
);
// New synthax
$var = [
'foo' => 'bar'
];
someone has an idea ?
I found a script that does the job perfectly !
https://github.com/thomasbachem/php-short-array-syntax-converter
I found out that it is also possible to do this with the php codesniffer: https://github.com/squizlabs/PHP_CodeSniffer
phpcbf src/ --standard=Generic --sniffs=Generic.Arrays.DisallowLongArraySyntax
In this example you have to replace src/ with the folder containing the scripts. Alternatively you can provide a file name.
Maybe a bit late, but I created my own. Maybe not pretty, but it does do the job I want. If you do not like tab, change \t in indent function to 2 or 4 spaces.
function loopArray(array $array, $loopcount = 0) {
$returnString = ($loopcount == 0) ? "[\n" : "";
$tabKey = indent($loopcount + 2);
$tabValue = indent($loopcount + 3);
$lastKey = array_key_last($array);
foreach ($array as $key => $value) {
$totalChildren = count($array[$key]);
$returnString .= $tabKey . '"' . $key . '" => ';
if ($totalChildren == 0) $returnString .= '[]';
if ($totalChildren > 0 && is_array($array[$key])) $returnString .= '[' . "\n";
if (is_array($value)) {
$returnString .= loopArray($value, $loopcount + 1);
} else {
if ($totalChildren == 1) $returnString .= '"' . $value . '"';
if ($totalChildren > 1) $returnString .= $tabValue . '"' . $value . '"' . ",\n";
}
$returnString .= ($lastKey == $key) ? "\n" . indent($loopcount+1) . "]" : ",\n";
}
return $returnString;
}
function indent($amount) {
return str_repeat("\t", $amount);
}
/** use function below only prior to php 7.3 */
function array_key_last(array $array) {
$key = NULL;
if ( is_array( $array ) ) {
end( $array );
$key = key( $array );
}
return $key;
}

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

How do I grab all parameters from a URL and print it out in PHP?

How do I print out all the parameters and their value from a URL without using e.g. print $_GET['paramater-goes-here']; multiple times?
I use
print_r($_GET);
foreach($_GET as $key => $value){
echo $key . " : " . $value . "<br />\r\n";
}
The parameters are in the URL, so are available in $_GET ; and you can loop over that array using foreach :
foreach ($_GET as $name => $value) {
echo $name . ' : ' . $value . '<br />';
}
Its easy to get all request parameters from url.
<?php
print_r($_REQUEST);
?>
This will return an array format.
You can also use parse_url() and parse_str():
$url = 'http://www.example.com/index.php?a=1&b=2&c=3&d=some%20string';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query);
parse_str($query, $arr);
echo $query; // a=1&b=2&c=3&d=some%20string
echo $a; // 1
echo $b; // 2
echo $c; // 3
echo $d; // some string
foreach ($arr as $key => $val) {
echo $key . ' => ' . $val . ', '; // a => 1, b => 2, c => 3, d => 4
}
Try this.....
function get_all_get()
{
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".$val;
}
return $output;
}
i use:
ob_start();
var_dump($_GET);
$s=ob_get_clean();
i use:
$get = $_REQUEST;
$query_string = '?';
foreach ($get as $key => $value) {
$query_string .= $key . '=' . $value . '&';
}
$query_string;

Categories