RegEx: Compare two strings to find Alliteration and Assonance

would be possible to Compare two strings to find Alliteration and Assonance?

i use mainly javascript or php

Tagged , , | Leave a comment

Why is a `switch` considered a looping structure for the purposes of `continue`?

I just got bit by assuming the following:

foreach ($arr as $key => $value) {
  switch($key) {
    // ... some other cases
    default:
      continue;
      // ^== assumption: move on to the next iteration of the foreach
      //     actual PHP: treat this continue just like a break
  }
  // ...
}

But in fact, according to the documentation for continue:

the switch statement is considered a looping structure for the purposes of continue.

Is there a reason for this choice on the part of PHP language designers? As far as I can tell, switch isn’t a looping control structure, so why treat it like one in this case?

Tagged , , | Leave a comment

PHP money_format(); £ sign not GBP

I cannot work out how to get the currency symbol?

At the moment I am using

setlocale(LC_MONETARY, 'en_GB');
money_format('%i', 1000);

Which give me the output

GBP1,000

But I want

£1,000

I have checked out the PHP manual but it isn’t that helpful.

Any ideas?

Tagged , | Leave a comment

Why are PHP errors printed twice?

Summary

Amazingly I could find nothing about this on Google or SO. When I throw an exception in PHP it appears in my console twice, complete with error message and stack trace. The first time it’s printed it says “PHP Fatal error: …” and the second time it just says “Fatal error: …”. I haven’t tested this is the Apache plugin version.

Example

With some namespaces and paths shortened with ‘…’ for safety:

$ php code/com/.../tabular_data.php
PHP Fatal error:  Uncaught exception 'Exception' with message 'File type not supported' in /home/codemonkey/.../tabular_data.php:56
Stack trace:
#0 /home/codemonkey/.../tabular_data.php(88): com...Tabular_Data->loadFromFile('/home/codemonke...', false)
#1 /home/codemonkey/.../tabular_data.php(95): com...Tabular_Data::fromFile('/home/codemonke...')
#2 {main}
  thrown in /home/codemonkey/.../tabular_data.php on line 56

Fatal error: Uncaught exception 'Exception' with message 'File type not supported' in /home/codemonkey/.../tabular_data.php:56
Stack trace:
#0 /home/codemonkey/.../tabular_data.php(88): com...Tabular_Data->loadFromFile('/home/codemonke...', false)
#1 /home/codemonkey/.../tabular_data.php(95): com...Tabular_Data::fromFile('/home/codemonke...')
#2 {main}
  thrown in /home/codemonkey/.../tabular_data.php on line 56

Question

I assume it has something to do with stderr and stdout both printing the error. In any case how do I ask PHP nicely to only print it once, preferably to stderr?


Version output

PHP 5.3.9 (cli) (built: Jan 11 2012 17:09:48)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies

The code

http://pastebin.com/iBUGJ2eY
This is the exact code that displays double exceptions for me, with namespaces and paths edited to foos. Note that I always get double exceptions in the command line on this installation. I’m all but certain that the issue lies in the PHP configuration.

Tagged , , | Leave a comment

MySQL GROUP BY UNIX TIMESTAMP

I’m trying to fetch a number of rows from a MySQL database and group them by the day they were posted.

End result I would like the following..

Monday
-Article 1
-Article 2
-Article 3

Tuesday
-Article 1
-Article 2

Wednesday
-Article 1
-Article 2
-Article 3
-Article 4

And so on, I’m not sure if this can be done in MySQL alone without PHP doing extra work.

This is the query I have so far but doesn’t seem to group by day.

SELECT
cms_news.news_id,
cms_news.news_title,
cms_news.news_date,
cms_news.news_category,
cms_news.news_source,
cms_news.news_type,
cms_news.news_content
FROM
cms_news cms_news,
GROUP BY
DAYOFMONTH(FROM_UNIXTIME(cms_news.news_date))
ORDER BY
cms_news.news_date DESC

Thanks.

Tagged , , | Leave a comment

What is best practice when it comes to storing images for a gallery?

My question is not about storing images on disk or in DB.

  • Images will be stored on disk
  • Image path and other image data will be saved in database.
  • Images will be given a unique filename
  • Images will be stored in 3 sizes
  • In time there may be many images used by many users

My questions are:
- Should images be stored in one folder, or many folders?
- Is it ok to use md5 for creating unique id’s? E.g. md5(id+filename+random_num)
- Should images be cached on server or on clients browser / computer?

Anything else I should think of?

The solution is using php, apache and mysql. We use Uploadify for uploading images.

Some code I use today

  /**
   * Calculate dir tree for object
   * Folders starts from 00 to FF (HEX) and can have just as
   * many subfolders (I think :)
   * @param $id - User ID
   * @param $type - Image category
   * @return string
   */
  function calculateDirTree($id, $type)
  {
      $hashUserID   = substr(hash('md5', $id), -4);
      $parentFolder = substr($hashUserID,0,2);
      $subfolder    = substr($hashUserID,2);
      $basePath     = $type."/".$parentFolder.'/'.$subfolder.'/';

      return $basePath;
  }
Tagged , , , | Leave a comment

vBulletin API to get member list and add member via PHP+cURL

Looking to do two things with the vBulletin API (v4.1.3) via PHP+cURL:

Get member list.
Add new user.

I am having a hard time finding any working examples of a php script which calls the API to do these things. Thanks in advance.

Tagged , , , | Leave a comment

How to calculate the difference between two days as a formatted string?

Here’s what I’ve got so far:

/**
 * Parse a duration between 2 date/times in seconds
 * and to convert that duration into a formatted string
 *
 * @param integer $time_start start time in seconds
 * @param integer $time_end   end time in seconds
 * @param string  $format     like the php strftime formatting uses %y %m %w %d %h or %i.
 * @param boolean $chop       chop off sections that have 0 values
 */
public static function FormatDateDiff($time_start = 0, $time_end = 0, $format = "%s", $chop = false) {

        if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start);

        list($year_start,$month_start,$day_start) = explode('-',date('Y-m-d',$time_start));
        list($year_end,$month_end,$day_end) = explode('-',date('Y-m-d',$time_end));

        $years = $year_end - $year_start;
        $months = $month_end - $month_start;
        $days = $day_start - $day_end;
        $weeks = 0;
        $hours = 0;
        $mins = 0;
        $secs = 0;

        if(mktime(0,0,0,$month_end,$day_end) < mktime(0,0,0,$month_start,$day_start)) {
            $years -= 1;
        }
        if($days < 0) {
            $months -= 1;
            $days += 30; // this is an approximation...not sure how to figure this out
        }
        if($months < 0) $months += 12;
        if(strpos($format, '%y')===false) {
            $months += $years * 12;
        }
        if(strpos($format, '%w')!==false) {
            $weeks = floor($days/7);
            $days %= 7;
        }
        echo date('Y-m-d',$time_start).' to '.date('Y-m-d',$time_end).": {$years}y {$months}m {$weeks}w {$days}d<br/>";
}

(It’s incomplete and inaccurate)

I can’t seem to get the math right. Naively dividing it out won’t work because of leap years and differing lengths of months.

The logic also needs to change depending on the format string. For example, passing 04-Feb-2010 to 28-Jun-2011 (as unix timestamps) with format string %y year %m month %d day should output 1 year 4 month 24 day but if %y year is omitted then it needs to add 12 months to the month, i.e., output should be 16 month 24 day.

Should handle times too…but I haven’t got to that yet.


None of these date_diff solutions handle weeks. And I don’t know how I could hack it into date_diff, so that’s not really a solution for me.

Furthermore, $diff->format doesn’t do what I asked…to give the total months and days if “bigger units” are omitted. Example:

>>> $start = new DateTime('04-Feb-2010')
>>> $end = new DateTime('28-Jun-2011')
>>> $diff = $start->diff($end)
>>> $diff->format('%m months, %d days')
'4 months, 24 days'

Should be 16 months, 24 days, as I stated earlier. Please stop being so quick to close my question as a dupe before you understand it fully. If the solutions to other questions can be tweaked to solve this, fine, but please explain how, because I don’t get it.

To be clear,

  • if %y is omitted, years should be rolled in the months
  • if %m is omitted, months should be rolled into the days
  • if %w is omitted, weeks should be rolled into the days
  • if %h is omitted, hours should be rolled into minutes
  • if %m is omitted, minutes should be rolled into seconds

If “smaller units” are omitted, the next biggest unit can be rounded or floored where it makes sense.

Tagged , , | Leave a comment

Image Gallery System – Which Approach is Better?

I am implementing an image upload system in PHP, The following are required:

  • Have categories
  • Allow users to comment on images
  • Allow rating of images

For that, I have 2 approaches in mind:

1. Implement the categorization by folders

Each category will have its own folder, and PHP will detect categories via those folders.

Pros

  • Structured look, easily locatable images.
  • Use of native PHP functions to manipulate and collect information about folders and files

Cons

  • Multiple categorization is a pain
  • Need to save the full path in the database

2. Implement the categorization by database

Each image in the database will have a catID (or multiple catIDs), and PHP will query the database to get the images

Pros

  • Easily implemented multi-categories
  • Only image name is saved

Cons

  • Seems more messy
  • Need to query the database a lot.

Which do you think is better? Or is there a third, completely different, approach that I’m missing?

Just a note, I don’t need code, I can implement that myself, I’m looking to find what to implement.

Would love to hear from you.

Tagged , | 3 Comments

Is there a way to set the scope of require_once() explicitly to global?

I’m looking for a way to set the scope of require_once() to the global scope, when require_once() is used inside a function. Something like the following code should work:

file `foo.php’:

<?php

$foo = 42;

actual code:

<?php

function includeFooFile() {
    require_once("foo.php"); // scope of "foo.php" will be the function scope
}

$foo = 23;

includeFooFile();
echo($foo."n"); // will print 23, but I want it to print 42.

Is there a way to explicitly set the scope of require_once()? Is there a nice workaround?

Tagged | Leave a comment
698 pages