PHP String Split - php

I need to split a string into chunks of 2,2,3,3 characters and was able to do so in Perl by using unpack:
unpack("A2A2A3A3", 'thisisloremipsum');
However the same function does not work in PHP, it gives this output:
Array
(
[A2A3A3] => th
)
How can I do this by using unpack? I don't want to write a function for it, it should be possible with unpack but how?
Thanks in advance,

Quoting the manual page of unpack :
unpack() works slightly different
from Perl as the unpacked data is
stored in an associative array.
To accomplish this you have to
name the different format codes and separate them by a slash /.
Which means that, using something like this :
$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);
You'll get the following output :
array
'first' => string 'th' (length=2)
'second' => string 'is' (length=2)
'third' => string 'isl' (length=3)
'fourth' => string 'ore' (length=3)

I've never used this function, but according to the documentation, the A character means "SPACE-padded string". So I'd hazard a guess that it's only taking the first two characters of the first word.
Have you tried unpack("A2A2A3A3", 'this is lorem ipsum'); ?

Related

Creating an API to pass an Array result in PHP

I am not an expert with PHP. I am creating an API in order to get some information from one of my website.
Here is the result of api.php:
array (size=4)
'price' => string '29.90' (length=5)
'activation_charge' => string '50.00' (length=5)
'decoder_price' => string '0.00' (length=4)
'is_offer' => int 0
I would like to create an API which would send these information. Here is the sample API call :
www.example.com/api.php?product=11&user=kiran
How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
Thanks
How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
JSON is a popular choice
json_encode http://php.net/json_encode
json_decode http://uk3.php.net/json_decode
XML is also another popular choice
http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
CSV is popular depending on the data/application (and variants of; pipe-delimiter, etc)
explode http://php.net/explode
If you want to return it to Javascript for example. The easiest way is to use JSON.
echo json_encode( $array ) ;
Which will output something like:
{ "price" : 29.9, "activation_charge" : 50.0, "decoder_price" : 0.0, "is_offer" : 0 }
Of course you can create your own format and decode it on the other side.

Failing preg_match pattern over entirely valid value

I used regexpal.com to test my regexp against the data Wordpress is trying to compare to and it fails, look at this and tell me if you see the problem?
The regexp
"#^json/(.+?)/?([a-zA-Z0-9]*)?$#"
The content to match
json/trips
These works, the previous one doesn't
json/trips/0
json/trips/13
json/fullticket/9805048001130122361809
If I try all these in regexpal they all work, but in wordpress, only the one that doesn't contain the id of the element I want to fetch fails the others work fine.
Interrestingly enough, the $matches return this:
array
0 => string 'json/trips' (length=10)
1 => string 't' (length=1)
2 => string 'rips' (length=4)
Try this regexp instead :
#^json/([^/]+)/?([a-zA-Z0-9]*)?$#
Output :
Array
(
[0] => json/trips
[1] => trips
[2] =>
)
The answer after tweaking the wordpress rewrite rule a bit more ends up being:
data/([^/]+)(/([a-zA-Z0-9\-]*))?$
Note: i changed json to data in the new scenario so i don't mess up the custom post type rules

PHP http_build_query special symbols

I want to create an url out of an array with the help of http_build_query (PHP). This is the Array:
$a = array("skip" => 1, "limit" => 1, "startkey" => '["naturalProduct","Apple"]')
After calling
$s = http_build_query($a);
I get the following string $s:
skip=1&limit=1&startkey=%5B%22naturalProduct%22%2C%22Apple%22%5D
My problem is, that I would need an url like this:
skip=1&limit=1&startkey=["naturalProduct","Apple"]
which means, that I don't want to convert the following symbols: ",[]
I have written a conversion function which I call after the http_build_query:
str_replace(array("%5B", "%22", "%5D", "%2C"), array('[', '"', ']', ','), $uri);
My question now: Is there a better way to reach the expected results?
My question now: Is there a better way to reach the expected results?
Yes, there is something better. http_build_query­Docs by default uses an URL encoding as outlined in RFC 1738. You just want to de-urlencode the string. For that there is a function that does this in your case: urldecode­Docs:
$s = http_build_query($a);
echo urldecode($s);
I hope you are aware that your URL then is no longer a valid URL after you've done that. You already decoded it.
You don't need to decode the special characters - they are automatically decoded when PHP's $_GET superglobal is generated. When I do print_r($_GET) with your generated string, I get this:
Array ( [skip] => 1 [limit] => 1 [startkey] => [\"naturalProduct\",\"Apple\"] )
Which has decoded every character, but hasn't unescaped the double quotes. To unescape them, use stripslashes():
echo stripslashes($_GET['startkey']);
This gives
["naturalProduct","Apple"]
Which you can then parse or use however you wish. A better solution, as ThiefMaster mentions in the comments, is to disabled magic_quotes_gpc in your php.ini; it's deprecated and scheduled for removal completely in PHP6.

Better data structure or algorithm than iterative searching on multidimensional arrays to find corresponding values?

For a site I am working on I use a library to get a list of states. It returns a numerically indexed array of states, each with three keys: stateCode, stateName, and stateSeg. It looks like this:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
array
'stateCode' => string 'AZ' (length=2)
'stateName' => string 'Arizona' (length=7)
'stateSeg' => string 'arizona-az' (length=10)
I often find myself with one of the three values and needing to look up its corresponding value. To do this I find myself constantly having to iterate through the array of states to find the data I need. Like this:
foreach ($this->data['stateList'] as $state)
{
if ($state['stateCode'] == $searchParams['state'])
{
$stateSeg = $state['stateSeg'];
break;
}
}
$url = BASEURL . '/' . $stateSeg . ".html";
This seems inefficient to me. I think the most efficient solution I’ve been able to come up with is to turn states into objects and put them in array with multiple keys for stateCode, stateSeg, and stateName each pointing to the same state object, so they can be referenced like this:
stateList[‘CA’]->getStateSeg();
or
stateList[‘Arizona’]->getStateCode();
or
stateList[‘alaska-ak’]->getStateName();
etc…
This also seems like kind of a hack which would result in a rather large array (150 keys pointing to 50 objects) with replicated data (keys replicating data stored within objects).
Anyway, just thought I’d see if there is some kind of pattern for this type of problem. This array of states isn't the only thing I’ve come across where I’ve had to do this sort of iterative searching on multidimensional arrays to find corresponding values.
Question is tagged PHP and the code above is in PHP, but I am interested in elegant solutions in any language.
If php supports references and I know the state, I'd just pass a reference to the appropriate array element and extract from it the necessary field.
Alternatively, if you never know in advance what state you can get, create and use a map (associative container/array), let its efficient implementation take care of quickly finding whatever you need. Seems like you may need several of them.
Also, I wonder if you could get rid of everything except the "alaska-ak" strings. The data appears highly redundant.
I think your basic idea with the object and the arrays is not that bad, but instead of creating actually objects, I would just refer to the existing objects (better: array data). Let's see your original list again:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
...
Each state object has an identifier, the array key: 0, 1, 2, ... .
All you need to do is to create three indexes based on key. You use the value as key (e.g. "AL" for "stateCode" index) and as value you take the array index, 0:
$indexStateCode['AL'] = 0;
You can then already look this up quickly:
$states[$indexStateCode['AL']];
Encapsulate this into a class with ArrayAccess and then on request instantiate the state object. You don't need it earlier.
Could you store the states in a mysql/sqlite table and use the database engine to do the lookup?
This seems inefficient to me
It isn't. Even worse-case, iterating through 50 items is probably an order of magnitude faster than querying a db.
a library to get a list of states
Not sure why you'd need a library to do this. But I'd either change the library to return the array how you need it, or wrap it in another module.
The data is somewhat redundant... All you need is two items: the state code and the state name. You can construct the "state seg" from those two. So keep a state code map and a state name map.

PHP file_exists and wildcard

Is there a way to write the PHP file_exists function so that it searches a directory for a file with an arbitrary extension. For instance, suppose I knew that a file were called "hello", but I didn't know the extension, how would I write a function that searched for a file called hello.* and returned the name of this file? As far as I can tell, file_exists will only search for a string.
Thanks.
You're looking for the glob() function.
file_exists doesn't do any kind of search : it only allows one to know whether a file exists or not, when knowing its name.
And, with PHP >= 5.3, you could use the new GlobIterator.
As an example with `glob()`, the following portion of code :
$list = glob('temp*.php');
var_dump($list);
Gives me this output :
array
0 => string 'temp-2.php' (length=10)
1 => string 'temp.php' (length=8)
While this one :
$list = glob('te*-*');
var_dump($list);
Yes, with two * ;-)
Will give me :
array
0 => string 'temp-2.php' (length=10)
1 => string 'test-1.php' (length=10)
2 => string 'test-curl.php' (length=13)
3 => string 'test-phing-1' (length=12)
4 => string 'test-phpdoc' (length=11)
As of PHP5.3, you can also use the GlobIterator to search a directory with wildcards:
$it = iterator_to_array(
new GlobIterator('/some/path/*.pdf', GlobIterator::CURRENT_AS_PATHNAME) );
would return the full paths to all .pdf files in some/path in an array. The above performs about the same as glob(), but iterators provide a more powerful and extensible API.
As long as file_exists returns a BOOLEAN I wrote this small function
that accepts a search string with * to look for files...
Example:
searchForFile("temp*");
function searchForFile($fileToSearchFor){
$numberOfFiles = count(glob($fileToSearchFor));
return ($numberOfFiles > 0);
}
If you need a little more control and are on pre PHP 5.3 you could use a DirectoryIterator or RecursiveDirectoryIterator. Both have a lot of great function for added control and manipulation.
PHP docs are at DirectoryIterator and RecursiveDirectoryIterator
You can use fnmatch to match one filename against a pattern. Use this in a loop over all files.
if (fnmatch("hello*", $filename)) {
echo 'true';
}

Categories