[PHP] Dynamically Modify URL Query String

I have to work with URL query string frequently. Often, I have to change and reconstruct the query portion based on certain rules. I wrote a function that takes in a URL string and an associative array, combines them and returns a new URL string. The resultant string can be used in <anchor> tags and also for HTTP GET request.

Usage example:

$url = 'http://www.example.com/index.php?id=123&name=orange#anchor';
$query1 = 'id=246&category=fruit shop';
$query2 = array('id'=>246, 'category'=>'fruit shop');
echo modifyQuery($url, $query1);
echo "<br />";
echo modifyQuery($url, $query2);

The $query parameter can be either a string or an associative array. In my usage example, both function calls return the same output.

NOTE: A valid URL string may contain username, password and port number. My function will not work with this information, but you can easily modify the function to retain these information. Have you noticed that the id has been changed from 123 to 246? The function’s $query parameter will appends+overwrites the query string.

Posted in Tao Of Programming at September 29th, 2009. No Comments.

[PHP] Underscore to Camelcase

Line 3 converts the input into lowercase, then it is split into words, using ‘_’ as delimiter.

The for..loop is used to join the words back. Before joining, the first character of each word is changed to uppercase. The trim is optional.

Posted in Tao Of Programming at April 6th, 2009. 3 Comments.

[PHP] Camel Case to Underscore

strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $str))

This piece of code turns a camel case string into a lowercase underscore version. (e.g.  'blackTableID' becomes 'black_table_id'). The regrex looks for capitalized letter (prefixed by a lowercase letter), add a underscore between these 2 letters. Finally, the strtolower function convert the resultant string to lowercase.

NOTE: If there are 2 consecutive capitalized letters, no underscore will be added.

Posted in Tao Of Programming at March 27th, 2009. 3 Comments.