1/22/09

Proved 1 + 1 = 2

Principia Mathematica is the book Russell wrote with Alfred North Whitehead where they gave a logical foundation of Mathematics by developing the Theory of Types that obviated the Russell's paradox. This
assertion may become more convincing after a look at the page 362 of Principia Mathematica where Russell and Whitehead finally proved that 1 + 1 = 2.

1/21/09

Installing PHPUnit / Selenium in XAMPP

A small how to install PHPUnit via PEAR in an XAMPP running on a windows box. A prerequisite for a continuous build strategy.

PHPUnit is a member of the xUnit family of testing frameworks and provides both a framework that makes the writing of tests easy as well as the functionality to easily run the tests and analyze their results.

Installing XAMPP

  • Download XAMPP from http://www.apachefriends.org/en/xampp.html
  • Unpack the zip, don't run any installer, just use the \xampp\xampp-control.exe to control the component (so the whole XAMPP directory can be moved to another drive without having absolute paths in all configurations files)

Installing PEAR

  • Execute \xampp\php\go-pear.bat and follow the onscreen instructions. The installation will modify the include_path in your php.ini file.
  • Execute \xampp\php\PEAR_ENV.reg to add PEAR to the windows registry

Installing PHPUnit

  • Open a command prompt
  • Execute pear channel-discover pear.phpunit.de
  • Execute pear install phpunit/PHPUnit
  • Now you should find PHPUnit installed in \xampp\php\PEAR\PHPUnit\

Installing Selenium

  • Execute pear install Testing_Selenium

Some useful pear commands to keep your PHP up to date

  • \xampp\php\pear list-upgrades
  • \xampp\php\pear upgrade-all

All pear Commands

build Build an Extension From C Source
bundle Unpacks a Pecl Package
channel-add Add a Channel
channel-alias Specify an alias to a channel name
channel-delete Remove a Channel From the List
channel-discover Initialize a Channel from its server
channel-info Retrieve Information on a Channel
channel-update Update an Existing Channel
clear-cache Clear Web Services Cache
config-create Create a Default configuration file
config-get Show One Setting
config-help Show Information About Setting
config-set Change Setting
config-show Show All Settings
convert Convert a package.xml 1.0 to package.xml 2.0 format
cvsdiff Run a "cvs diff" for all files in a package
cvstag Set CVS Release Tag
download Download Package
download-all Downloads each available package from the default channel
info Display information about a package
install Install Package
list List Installed Packages In The Default Channel
list-all List All Packages
list-categories List All Categories
list-category List All Packages of a Category
list-channels List Available Channels
list-files List Files In Installed Package
list-packages List All Packages of a Channel
list-upgrades List Available Upgrades
login Connects and authenticates to remote server
logout Logs out from the remote server
makerpm Builds an RPM spec file from a PEAR package
package Build Package
package-dependencies Show package dependencies
package-validate Validate Package Consistency
pickle Build PECL Package
remote-info Information About Remote Packages
remote-list List Remote Packages
run-scripts Run Post-Install Scripts bundled with a package
run-tests Run Regression Tests
search Search remote package database
shell-test Shell Script Test
sign Sign a package distribution file
uninstall Un-install Package
update-channels Update the Channel List
upgrade Upgrade Package
upgrade-all Upgrade All Packages
Usage: pear [options] command [command-options]
Type "pear help options" to list all options.
Type "pear help shortcuts" to list all command shortcuts.
Type "pear help " to get the help for the specified command.

Khung ảnh

Winter Frame


Mã:
http://rapidshare.com/files/186643608/fwin_thuytinhtim.rar.html


Flower Frames


Mã:
http://rapidshare.com/files/186648628/psd-flower.rar.html


PNG Wedding Frames


Mã:
http://rapidshare.com/files/186671935/frameswed_thuytinhtim.rar.html


Wedding Frames Collection


Mã:
http://rapidshare.com/files/186669926/wfc_thuytinhtim.rar


PSD Wedding Frames


Mã:
http://rapidshare.com/files/186659225/wedfra_thuytinhtim.rar


Love Frames


Mã:
http://rapidshare.com/files/186658090/luvframe_thuytinhtim.rar


New Year Frames Pack


Mã:
http://rapidshare.com/files/186677845/newyfrcol_thuytinhtim.rar


Love Photo Frames


Mã:
http://rapidshare.com/files/186657825/lf_thuytinhtim.rar


Calender 2009 Collection


Mã:
http://rapidshare.com/files/186668852/calen09rus_thuytinhtim.rar


Weeding Frames-Hearts


Mã:
http://rapidshare.com/files/186675464/hwfp_thuytinhtim.rar


Children Frames-Pooh


Mã:
http://rapidshare.com/files/186669033/cpfp_thuytinhtim.rar


Beautiful Frameworks for Wedding Album


Mã:
http://rapidshare.com/files/186680832/Wedding_nabor.rar


PSD Calender 2009


Mã:
http://rapidshare.com/files/186668439/c09_thuytinhtim.rar


Wedding Frames


Mã:
http://rapidshare.com/files/186659522/wfc_thuytinhtim.rar


Donald Duck Frame PSD


Mã:
http://rapidshare.com/files/186669066/donaldduck_thuytinhti

Hackintosh Tutorial: Install a Mac Leopard OS X Retail DVD on a PC


September 4th, 2008 Posted in Hackintosh

After building hackintosh machines using different modified OS X installers, the hackintosh community has come a long way and is within grasp of achieving the holy grail of running Mac OS X on PCs—installing the original, unmodified OS X DVDs created by Apple for Macs on ordinary IBM compatible personal computers. Well, almost.

While we can now use a retail Mac OS X DVD to turn our PC into a hackintosh, we still need a bootloader to get it to recognize and install OS X the first time. The good news is, after a successful installation, we can now install any updates from Apple without breaking our system or reinstall the operating system without having to add the same kexts (drivers) that we already have that makes our non-Mac standard hardware peripherals work.

Pre-requisites

  • A PC with Intel Core Processors and Chipset (AMD is not yet supported).
  • A Blank CD (for Boot-132).
  • A retail Mac OS X DVD Installer (not an Upgrade OS X DVD).
  • Download the Leopard 10.5.4 ComboUpdate here.
  • Download the Chameleon for Hard Disk here.
  • Download the Boot-132 Generic ISO here.
  • Download EFIStudio here.

Step 1. Before You Begin

Burn the Boot-132 Generic ISO on a CD. This BootCD should work fine for most hardware configurations; after which, it should be able to install the retail OS X DVD. If this doesn’t work for you, you may need to modify the contents and add the necessary kexts for your hardware. More info here.

Step 2. Install Leopard.

1. Insert your BootCD and boot/start your PC.
2. On the boot prompt, press Enter. You will be asked to enter a two-digit hexadecimal boot device (do not enter anything yet).
3. Remove the BootCD and replace it with the Mac OS X Retail DVD. Wait for the blinking light on your DVD drive to stop and then hit Enter (this will read your DVD drive and not your HD).

Hint: If you keep going back to the bootloader, it only means you don’t have the correct Retail Mac OS X DVD Installer. The best solution is to buy one.

4. Perform the Mac OS X Leopard installation. You may need to use Disk Utility (under the Utilities Menu) to partition and format your HD if you haven’t already. Make sure to select GUID (under Options).
5. Restart after the installation and replace the Retail Mac OS X DVD with the BootCD.
6. On the boot prompt, press Enter. This time, enter the two-digit hexadecimal of the drive where you installed OS X. Enter 80; if it doesn’t show the startup volume of your OS X, hit Esc. Try 81, and so on until you see your OS X volume. Select it and hit Enter.
7. You should now be in Leopard.

Step 3. Update Leopard to 10.5.4

1. Install the 10.5.4 ComboUpdate.
2. Reboot with the BootCD and enter the same two-digit hex you entered before. Select your startup volume and type -v -f (you don’t have to enter these the next time), and press Enter.
3. At this point, you still won’t be able to boot your hackintosh without the BootCD.

Step 4. Install Chameleon

The Chameleon for Hard Disk you downloaded above has the following files:

  • Chameleon_DFE_for_Hard_Disk.dmg
  • OSX86Tools
  • EFIStudio

1. Open Chameleon.
2. Copy the contents of the Extra directory from the Generic.iso CD by dragging it to the Extra Contents folder in Chameleon.

Hint: To do this, you need to perform the following:

  • Open the Generic.iso CD from your desktop.
  • Double-click on the INITRD.IMG file.
  • Double-click on the Extra folder.
  • Drag the Extensions folder to the Extra Contents folder in Chameleon

3. Double-click the Chameleon_DFE_for_Hard_Disk.pkg file and install to your hard disk.
4. Remove the BootCD and reboot.
5. You should now be able to boot into Leopard without the BootCD.

Step 5. Fix Your Hardware Peripherals

After upgrading to 10.5.4, some of your hardware peripherals (i.e. video, network card, audio, etc.) may no longer work. Even the kexts that worked for my previous modified OS X installations don’t work with the latest version so I had to scour the net for a fix. Depending on what you have installed on your PC, you may need different solutions. Below are the fixes I applied for my own peripherals.

Network Fix:

Taken from the IONetworkingFamily.kext included in the GA-965P-DS3_ISO bootcd.

Audio Fix:

Taken from the AppleAzaliaAudio.kext included in the Generic.iso BootCD.

Restart/Reboot Fix:

Replace your AppleACPIPlatform.kext with this.

Shutdown Fix:

Download and install this.

Hint: To easily install kexts, you may want to use the OSX86 Tools. Read more about the OSX86 Tool here. You can also use the EFI Studio to try adding EFI Strings to your Boot.plist in case you have problems with video or audio kexts. Read more about EFI here.

Video (Nvidia 7200GS) Fix (QE/CI):

This one gave me the biggest headache. The video kexts or injectors (Nvinject, NvInstaller) that worked for me in the past, no longer works after upgrading to 10.5.4. I tried many versions and none worked. I tried adding device strings to com.apple.Boot.plist using EFIStudio and deleting all video injectors in Extensions and still a no go. I tried to manually edit the kexts by entering my device ID, etc., and still no QE/CI support. Finally, I found out that the Generic.iso BootCD has Nvkush.kext in it and by installing Chameleon, it aslo installed it to my hard drive. So I just deleted it from the /Extra/Extensions folder and made sure I had my video device string in the com.apple.Boot.plist using EFIStudio, reboot and voila!

Now you have a Hackintosh that is as close to a real Mac in terms of the underlying software program. You can safely use Software Update to install updates directly from Apple to your PC.

To get a real Mac experience, buy a Mac!

Những dự đoán ngớ ngẩn nhất trong thế giới công nghệ

Khi nói về tương lai, không ít những “cây đại thụ” về công nghệ cũng đoán sai, thậm chí còn sai bét so với thực tế diễn ra. Dưới đây là tổng kết 7 dự đoán ngớ ngẩn trong lĩnh vực công nghệ 65 năm qua. “Thế giới sẽ chỉ có 5 chiếc máy tính!”

Câu nói “nổi tiếng” này là của Thomas Watson, Chủ tịch IBM năm 1943. Vào buổi bình minh của ngành công nghiệp điện toán, không ai có thể biết chắc chắn rằng công nghệ mới này sẽ đưa con người đi đến đâu. Nhưng sự bùng nổ của máy tính để bàn sau đó đã giúp cho chiếc PC có mặt trên hầu hết các hộ gia đình. Có thể vào thời gian đó, Thomas Watson ngụ ý rằng đó là những chiếc máy tính chạy bằng ống chân không có kích cỡ to như ngôi nhà. Quả thực với một chiếc máy tính khổng lồ như thế thì chẳng có ai lại muốn mang chúng về nhà cả.

“TV sẽ không thể trụ vững trên thị trường”

Năm 1946, Giám đốc xưởng phim 20th Century Fox, Darryl Zanuck nói rằng TV sẽ không thể tồn tại sau 6 tháng kể từ khi nó xuất hiện bởi “mọi người sẽ cảm thấy chán ngắt với chiếc hộp gỗ”. Vào thời điểm đó, 20th Century Fox đã sản xuất được hơn 100 bộ phim lớn trên màn hình bạc. Chính vì thế chẳng có lý do gì để Darryl Zanuck tin rằng những chiếc TV với màn hình bé tí lại sống sót cả.

“Máy hút bụi bằng năng lượng hạt nhân sẽ xuất hiện trong 10 năm tới”

Đó là dự đoán của Alex Lewyt, Chủ tịch công ty Lewyt, được đưa ra năm 1955. Những năm 50 của thế kỷ, chủ đề hạt nhân trở thành “hot” trên mọi phương tiện thông tin đại chúng. Người ta thậm chí còn “choáng hơn” khi Alex Lewyt tuyên bố rằng hãng của ông sẽ nhanh chóng tạo ra chiếc máy hút bụi chạy bằng năng lượng hạt nhân trong khoảng 10 năm, tức là năm 1965. Thực tế đó đã không bao giờ xảy ra bởi năng lượng hạt nhân là lĩnh vực cực kỳ phức tạp, mang tầm cỡ quốc gia chứ không phải là lĩnh vực để các doanh nghiệp nhảy vào.

“Chẳng có lý do gì mà người ta phải dùng máy tính tại nhà”

Câu nói “nổi tiếng” này là của Ken Olsen, sáng lập hãng Digital Equipment Corporation (DEC), năm 1977. Cách đây 10 năm, DEC đã được hãng Compaq mua lại, nhưng vào những năm 70 của thế kỷ, DEC là một tên tuổi lớn trong ngành công nghiệp máy tính. Sau 4 năm kể từ tuyên bố của Ken Olsen, chiếc máy tính đầu tiên của IBM ra mắt đã phần nào đánh đổ giả thuyết này.

“Apple đã chết!”

Thực ra thì đây không phải lời nguyền rủa đầu tiên của các nhân vật chóp bu Microsoft dành cho đối thủ Apple. Nhận định có phần cay độc này là của Nathan Myhrvold, cựu giám đốc công nghệ Microsoft năm 1997.

Công bằng mà nói thì vào thời điểm đó cũng có nhiều yếu tố để Nathan Myhrvold đưa ra nhận định trên. Tuy nhiên, 10 năm sau không những Apple không chết mà còn vươn lên là hãng công nghệ hàng đầu thế giới với những cải tiến và sản phẩm sáng tạo mà không phải hãng này cũng có được. Những sản phẩm đỉnh cao của Apple như máy Mac, iPod, iPhone luôn được cộng đồng người dùng đánh giá cao ở sự sáng tạo, tính nghệ thuật, mức độ hữu dụng và khả năng công nghệ đỉnh cao.

“Hai năm nữa, thư rác sẽ không còn”

Đó là tiên đoán của Chủ tịch Microsoft Bill Gates năm 2004, nhưng thực tế lại trái ngược hoàn toàn. Những thống kê gần đây cho thấy lượng thư rác đã chiếm gần 92% e-mail lưu thông trên toàn cầu. Các biện pháp ngăn chặn thư rác tỏ ra không mấy hữu ích, và bản thân Microsoft cũng chưa có giải pháp hữu hiệu nào cho việc này. Nói vậy để biết rằng không phải dự đoán nào của một người được coi là nhân tài như Bill Gates cũng trở thành hiện thực.

1/15/09

Virus Effect Remover v2.3 - Khắc phục hậu quả virus

Virus Effect Remover là 1 công cụ nhỏ gọn và miễn phí, giúp cho bạn khắc phục các lỗi trong Windows Registry và hệ thống file do virus gây ra. Nó cũng có tác dụng phát hiện những lỗi trong Registry và mở lại Task Manager, Registry Editor, Folder Option, …

----------------------------------


Virus Effect Remover
is the tool which help you to remove the effect of virus from windows registry and file system. It also detect the registry error caused by virus and enables the Blocked content like task manager, registry editor, folder option etc.

Virus Effect Remover v2.3 - Khắc phục hậu quả virus Homepage:

http://sourceforge.net/projects/viruseffectremo/


Virus Effect Remover v2.3 - Khắc phục hậu quả virus Download:

http://downloads.sourceforge.net/viruseffectremo/Virus_Effect_Remover2.3.exe?modtime=1231782018&big_mirror=0

9 Promising PHP Template Engines

PHP template engines are used widely to seperate the code & the layout.

PHP LogoThis makes a website easier to maintain/update & creates a better development environment by enabling developers & designers to work together easier.

It sure has some drawbacks which is generally the performance (most libraries offer great solutions there) & need to learn a new syntax (not always).

To mention, using a template engine may not be suitable for every project. A website with few pages will probably won’t need it. But it can improve the development process of a portal, an e-commerce site or another web application easily.

Here are 19 PHP template engines with very nice features & have a continious development:

Smarty

Smarty PHP Template Engine

The most popular PHP templating engine which prefers to call itself a "template/presentation framework" as it equips both the designer & programmers with powerful tools at the presentation layer.

It has a robust caching mechanism as well as a strong plug-in & add-on support.

With the template functions, debugging capabilities, security it provides & continious development, Smarty is a great engine.

Dwoo

Dwoo PHP Template Engine

Dwoo aims to be a serious alternative to Smarty with a cleaner codebase.

It has almost a totally compatible template & plugin system with Smarty.

Some main features are:

  • Template Inheritance, a fresh look at complex template structures, now built without includes.
  • Flexible plugin creation.
  • Scope aware engine, allowing for shorter templates.
  • Unicode / UTF-8 support for string manipulation functions & more..

Savant

Savant PHP Template Engine

A lightweight templating engine for PHP.

it uses PHP itself as its template language & no need to learn a new markup system.

Template Blocks

Template Blocks PHP Template Engine

Template Blocks is a visual template engine, replacing any semantics of previous generation engines with an AJAX interface.

The engine is lightweight, flexible & extensible.

You can give any section with static content any extension of these popular extensions you like: .html, .htm or .php. They will all load up the same content!

Open Power Template

Open Power Template PHP

The new Open Power Template contains a built-in XML parser that fully understands the structure of your HTML code. It can find unclosed tags and perform complex operations on its structure.

For a better performance, every template is compiled into the PHP code, so that its execution is fast and can be speeded with the PHP accelerators. And results are cached.

TinyButStrong

Tiny But Strong PHP Template Engine

A very easy to learn & implement templating system.

It is only 1 file, 1 PHP class with 6 methods & 5 properties.

Simplicity is its power. It can connect to any database, has a caching system & provides easy date-time and numeric formats.

Rain TPL

Rain PHP Template Engine

An easy to use and install engine which has 6 tags, 3 PHP functions and 2 PHP classes.

Rain TPL is WYSIWYG friendly, you can work with img/css relative paths & they are converted to the correct server path.

PHPTAL

PHPTAL PHP Template Engine

PHPTAL is a PHP implementation of ZPT. To be short, PHPTAL is a XML/XHTML template library for PHP.

While most web developpers continue to use PHP tags as the core language of their templates, the Zope community came with a refreshing idea named TAL which is moving presentation actions inside XHTML attributes instead of using plain tags or elements.

PHP Template Engine

PHP Template Engine

This PHP templating engine uses PHP, not a template scripting language.

It has a straightforward user authentication, session & cookie system. There is a built-in support for MySQL connections & your own classes/functions can be added with ease.

Template Lite

Template Lite - PHP Template Engine

Template Lite, previously known as Smarty Light, is a drop in replacement for Smarty.

It supports most of the features of Smarty. Also, mentioned to be faster & consumes less memory compared to Smarty.

VTE - Vivvo Template Engine

Vivvo PHP Template Engine

VTE, originally built for Vivvo CMS but distributed for free, is light-weight, easy to use, yet powerful and scalable.

The template engine that can do recursions, object calls, arrays, but still remain within a single class in less than 1000 lines of code!

VTE language is XML-based and it consists of tags and attributes.

XTemplate

XTemplate PHP Template Engine

XTemplate allows you to store your HTML code separately from your PHP code.

It has many useful features yet code is short, highly optimized & used in various commercial & open source projects.

vlibTemplate

vlib PHP Template Engine

vlibTemplate is a class for templating PHP applications. It is normally included in the vlib package which has the following 3 classes:

  • vlibTemplate
  • vlibDate
  • vlibMimeMail

Using this class you set the values for the variables, loops, if statements, etc. which are declared in the template. This enables you to separate all of the design from the data, which you create using PHP.

PHP-Sugar

PHP-Sugar Template Engine

It has a similar spirit with Smarty.

A flexible compilation engine that allows expressions similar to that of PHP itself is used. It also has a clean and easy to understand syntax.

Output is HTML-escaped by default, instead of requiring explicit escaping like PHP itself, which makes it far less likely to accidentally introduce an HTML or JavaScript code injection vulnerability from user-submitted content.

FXL Template

FXL PHP Template Engine

FXL Template an easy to use template engine covering all the basic features of a template system.

It supports:

  • simple text/array assignments
  • blocks
  • nested blocks.

The template markup is really easy to learn & for high traffic enviroments a "memcached" cache extension exists.

Blitz templates

Blitz Templates

Blitz templates is a fast template engine written in C and compiled as a PHP module.

It started as a php_templates replacement, but developed into much more. It is based on extensible template controllers (PHP) and weakly-active templates (HTML).

Vemplator

Vemplator PHP Template Engine

With 220 lines of code, Vemplator offers:

  • Conditionals: if/else and switch statements
  • Dot-notation for class member variables (customer.name)
  • Associative and numerical arrays (row[0] and rows[1]['name'])
  • For-each looping over arrays (associative and numerically indexed)
  • Includes (included templates are parsed and cached separately)

Template Engines Under PEAR

PHP PEAR Template Engine

4 PEAR packages on templating:

QuickSkin

QuickSkin PHP Template Engine

QuickSkin, previously known as SmartTemplate, works like a ‘template compiler’ that converts templates into executable PHP code and stores it for later reuse.

It supports:

  • Simple Scalar Substitution (Strings, etc.)
  • Block Iterations (nested Arrays / BEGIN..END)
  • Basic Control Structures (IF..ELSEIF..ELSE)
  • Custom Extension (Output filters, uppercase, sprintf, etc.)
  • Template Compilation (HTML templates are converted to executable PHP Code)
  • Output Caching (Accelerates your applications by reusing page output)

What is your preference of PHP template engines & why?

1/14/09

PHP regular expressions examples

Mastering Regular Expressions
Mastering Regular Expressions quickly covers the basics of regular-expression syntax, then delves into the mechanics of expression-processing, common pitfalls, performance issues, and implementation-specific differences. Written in an engaging style and sprinkled with solutions to complex real-world problems, MRE offers a wealth information that you use. I will start with some simple usage examples of the regular expressions and continue with a huge list of cases for various situations where we would normally need a regex to operate. We will use simple functions which return TRUE or FALSE. $regex will serve as our regular expression to match against and $text will be our text (pretty obvious):

function do_reg($text, $regex)
{
if (preg_match($regex, $text)) {
return TRUE;
}
else {
return FALSE;
}
}

The next function will get the part of a given string ($text) matched by the regex ($regex) using a group srorage ($regs). By changing the $regs[0] to $regs[1] we can use a capturing group (in this case griup 1) to match against. The capturing group can also have a name ($regs['groupname']):

function do_reg($text, $regex, $regs)
{
if (preg_match($regex, $text, $regs)) {
$result = $regs[0];
}
else {
$result = "";
}
return $result;
}

The following function will return an array of all regex matches in a given string ($text):

function do_reg($text, $regex)
{
preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
return $result = $result[0];
}

Next we can iterate (loop) over all matches in a string ($text) and output the results:

function do_reg($text, $regex)
{
preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
$result[0][$i];
}
}

Extending the above one we can iterate over all matches ($text) and capture groups in a string ($text):

function do_reg($text, $regex)
{
preg_match_all($regex, $text, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) {
$result[$matchi][$backrefi];
}
}
}
}

REGULAR EXPRESSION EXAMPLES BY SITUATIONS AND NEEDS: Addresses

//Address: State code (US)
'/\\b(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])\\b/'

//Address: ZIP code (US)
'\b[0-9]{5}(?:-[0-9]{4})?\b'

Columns

//Columns: Match a regex starting at a specific column on a line.
'^.{%SKIPAMOUNT%}(%REGEX%)'

//Columns: Range of characters on a line, captured into backreference 1
//Iterate over all matches to extract a column of text from a file
//E.g. to grab the characters in colums 8..10, set SKIPAMOUNT to 7, and CAPTUREAMOUNT to 3
'^.{%SKIPAMOUNT%}(.{%CAPTUREAMOUNT%})'

Credit cards

//Credit card: All major cards
'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$'

//Credit card: American Express
'^3[47][0-9]{13}$'

//Credit card: Diners Club
'^3(?:0[0-5]|[68][0-9])[0-9]{11}$'

//Credit card: Discover
'^6011[0-9]{12}$'

//Credit card: MasterCard
'^5[1-5][0-9]{14}$'

//Credit card: Visa
'^4[0-9]{12}(?:[0-9]{3})?$'

//Credit card: remove non-digits
'/[^0-9]+/'

CSV

//CSV: Change delimiter
//Changes the delimiter from a comma into a tab.
//The capturing group makes sure delimiters inside double-quoted entries are ignored.
'("[^"\r\n]*")?,(?![^",\r\n]*"$)'

//CSV: Complete row, all fields.
//Match complete rows in a comma-delimited file that has 3 fields per row,
//capturing each field into a backreference.
//To match CSV rows with more or fewer fields, simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)$'

//CSV: Complete row, certain fields.
//Set %SKIPLEAD% to the number of fields you want to skip at the start, and %SKIPTRAIL% to
//the number of fields you want to ignore at the end of each row.
//This regex captures 3 fields into backreferences. To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPTRAIL%}$'

//CSV: Partial row, certain fields
//Match the first SKIPLEAD+3 fields of each rows in a comma-delimited file that has SKIPLEAD+3
//or more fields per row. The 3 fields after SKIPLEAD are each captured into a backreference.
//All other fields are ignored. Rows that have less than SKIPLEAD+3 fields are skipped.
//To capture more or fewer fields, simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, leading fields
//Match the first 3 fields of each rows in a comma-delimited file that has 3 or more fields per row.
//The first 3 fields are each captured into a backreference. All other fields are ignored.
//Rows that have less than 3 fields are skipped. To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, variable leading fields
//Match the first 3 fields of each rows in a comma-delimited file.
//The first 3 fields are each captured into a backreference.
//All other fields are ignored. If a row has fewer than 3 field, some of the backreferences
//will remain empty. To capture more or fewer fields, simply duplicate or delete the capturing groups.
//The question mark after each group makes that group optional.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)?,("[^"\r\n]*"|[^,\r\n]*)?'

Dates

//Date d/m/yy and dd/mm/yyyy
//1/1/00 through 31/12/99 and 01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}\b'

//Date dd/mm/yyyy
//01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9]{2}'

//Date m/d/y and mm/dd/yyyy
//1/1/99 through 12/31/99 and 01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
//Accepts dashes, spaces, forward slashes and dots as date separators
'\b(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}\b'

//Date mm/dd/yyyy
//01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
'(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}'

//Date yy-m-d or yyyy-mm-dd
//00-1-1 through 99-12-31 and 1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'\b(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])\b'

//Date yyyy-mm-dd
//1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'

Delimiters

//Delimiters: Replace commas with tabs
//Replaces commas with tabs, except for commas inside double-quoted strings
'((?:"[^",]*+")|[^,]++)*+,'

Email addresses

//Email address
//Use this version to seek out email addresses in random documents and texts.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the regex to random documents.
'\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'

//Email address (anchored)
//Use this anchored version to check if a valid email address was entered.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Requires the "case insensitive" option to be ON.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$'

//Email address (anchored; no consecutive dots)
//Use this anchored version to check if a valid email address was entered.
//Improves on the original email address regex by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the regex to random documents.
'^[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$'

//Email address (no consecutive dots)
//Use this version to seek out email addresses in random documents and texts.
//Improves on the original email address regex by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Including these increases the risk of false positives when applying the regex to random documents.
'\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b'

//Email address (specific TLDs)
//Does not match email addresses using an IP address instead of a domain name.
//Matches all country code top level domains, and specific common top level domains.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|biz|info|name|aero|biz|info|jobs|museum|name)$'

//Email address: Replace with HTML link
'\b(?:mailto:)?([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b'

HTML

//HTML comment
'<!--.*?-->'

//HTML file
//Matches a complete HTML file. Place round brackets around the .*? parts you want to extract from the file.
//Performance will be terrible on HTML files that miss some of the tags
//(and thus won't be matched by this regular expression). Use the atomic version instead when your search
//includes such files (the atomic version will also fail invalid files, but much faster).
'<html>.*?<head>.*?<title>.*?</title>.*?</head>.*?<body[^>]*>.*?</body>.*?</html>'

//HTML file (atomic)
//Matches a complete HTML file. Place round brackets around the .*? parts you want to extract from the file.
//Atomic grouping maintains the regular expression's performance on invalid HTML files.
'<html>(?>.*?<head>)(?>.*?<title>)(?>.*?</title>)(?>.*?</head>)(?>.*?<body[^>]*>)(?>.*?</body>).*?</html>'

//HTML tag
//Matches the opening and closing pair of whichever HTML tag comes next.
//The name of the tag is stored into the first capturing group.
//The text between the tags is stored into the second capturing group.
'<([A-Z][A-Z0-9]*)[^>]*>(.*?)</\1>'

//HTML tag
//Matches the opening and closing pair of a specific HTML tag.
//Anything between the tags is stored into the first capturing group.
//Does NOT properly match tags nested inside themselves.
'<%TAG%[^>]*>(.*?)</%TAG%>'

//HTML tag
//Matches any opening or closing HTML tag, without its contents.
'</?[a-z][a-z0-9]*[^<>]*>'



IP addresses

//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple regex if you know the data does not contain invalid IP addresses.
'\b([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\b'

//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple regex if you know the data does not contain invalid IP addresses,
//and you don't need access to the individual IP numbers.
'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this regex to match IP numbers with accurracy, without access to the individual IP numbers.
'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this regex to match IP numbers with accurracy.
//Each of the 4 numbers is stored into a capturing group, so you can access them for further processing.
'\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

Lines

//Lines: Absolutely blank (no whitespace)
//Regex match does not include line break after the line.
'^$'

//Lines: Blank (may contain whitespace)
//Regex match does not include line break after the line.
'^[ \t]*$'

//Lines: Delete absolutely blank lines
//Regex match includes line break after the line.
'^\r?\n'

//Lines: Delete blank lines
//Regex match includes line break after the line.
'^[ \t]*$\r?\n'

//Lines: Delete duplicate lines
//This regex matches two or more lines, each identical to the first line.
//It deletes all of them, except the first.
'^(.*)(\r?\n\1)+$'

//Lines: Truncate a line after a regex match.
//The regex you specify is guaranteed to match only once on each line.
//If the original regex you specified should match more than once,
//the line will be truncated after the last match.
preg_replace('^.*(%REGEX%)(.*)$', '$1$2', $text);

//Lines: Truncate a line before a regex match.
//If the regex matches more than once on the same line, everything before the last match is deleted.
preg_replace('^.*(%REGEX%)', '$1', $text);

//Lines: Truncate a line before and after a regex match.
//This will delete everything from the line not matched by the regular expression.
preg_replace('^.*(%REGEX%).*$', '$1', $text);

Logs

//Logs: Apache web server
//Successful hits to HTML files only. Useful for counting the number of page views.
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?\.html?)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)200\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'

//Logs: Apache web server
//404 errors only
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)404\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'

Numbers

//Number: Currency amount
//Optional thousands separators; optional two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?\b'

//Number: Currency amount
//Optional thousands separators; mandatory two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}\b'

//Number: floating point
//Matches an integer or a floating point number with mandatory integer part. The sign is optional.
'[-+]?\b[0-9]+(\.[0-9]+)?\b'

//Number: floating point
//Matches an integer or a floating point number with optional integer part. The sign is optional.
'[-+]?\b[0-9]*\.?[0-9]+\b'

//Number: hexadecimal (C-style)
'\b0[xX][0-9a-fA-F]+\b'

//Number: Insert thousands separators
//Replaces 123456789.00 with 123,456,789.00
'(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))'

//Number: integer
//Will match 123 and 456 as separate integer numbers in 123.456
'\b\d+\b'

//Number: integer
//Does not match numbers like 123.456
'(?<!\S)\d++(?!\S)'

//Number: integer with optional sign
'[-+]?\b\d+\b'

//Number: scientific floating point
//Matches an integer or a floating point number.
//Integer and fractional parts are both optional.
'[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?'

//Number: scientific floating point
//Matches an integer or a floating point number with optional integer part.
//Both the sign and exponent are optional.
'[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b'

Passwords

//Password complexity
//Tests if the input consists of 6 or more letters, digits, underscores and hyphens.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}\z'

//Password complexity
//Tests if the input consists of 6 or more characters.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z'

File paths

//Path: Windows
'\b[a-z]:\\[^/:*?"<>|\r\n]*'

//Path: Windows
//Different elements of the path are captured into backreferences.
'\b((?#drive)[a-z]):\\((?#folder)[^/:*?"<>|\r\n]*\\)?((?#file)[^\\/:*?"<>|\r\n]*)'

//Path: Windows or UNC
'(?:(?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\[^/:*?"<>|\r\n]*'

//Path: Windows or UNC
//Different elements of the path are captured into backreferences.
'((?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\((?#folder)[^/:*?"<>|\r\n]*\\)?((?#file)[^\\/:*?"<>|\r\n]*)'

Phone numbers

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
//Replaces all those with (333) 444-5555
preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
'\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}'

Postal codes

//Postal code (Canada)
'\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\b'

//Postal code (UK)
'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b'

Programming

//Programming: # comment
//Single-line comment started by # anywhere on the line
'#.*$'

//Programming: # preprocessor statement
//Started by # at the start of the line, possibly preceded by some whitespace.
'^\s*#.*$'

//Programming: /* comment */
//Does not match nested comments. Most languages, including C, Java, C#, etc.
//do not allow comments to be nested. I.e. the first */ closes the comment.
'/\*.*?\*/'

//Programming: // comment
//Single-line comment started by // anywhere on the line
'//.*$'

//Programming: GUID
//Microsoft-style GUID, numbers only.
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//(Long version, if your regex flavor doesn't support conditionals.)
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}|\([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\)|\{[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//Short version, illustrating the use of regex conditionals. Not all regex flavors support conditionals.
//Also, when applied to large chunks of data, the regex using conditionals will likely be slower
//than the long version. Straight alternation is much easier to optimize for a regex engine.
'(?:(\()|(\{))?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}(?(1)\))(?(2)\})'

//Programming: Remove escapes
//Remove backslashes used to escape other characters
preg_replace('\\(.)', '\1', $text);

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string may span multiple lines.
'"[^"\\]*(?:\\.[^"\\]*)*"'

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string cannot span multiple lines.
'"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"'

//Programming: String
//Quotes may not appear in the string. The string cannot span multiple lines.
'"[^"\r\n]*"'

Quotes

//Quotes: Replace smart double quotes with straight double quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace('[\x84\x93\x94]', '"', $text);

//Quotes: Replace smart double quotes with straight double quotes.
//Unicode version for use with Unicode regex engines.
preg_replace('[\u201C\u201D\u201E\u201F\u2033\u2036]', '"', $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//Unicode version for use with Unicode regex engines.
preg_replace("[\u2018\u2019\u201A\u201B\u2032\u2035]", "'", $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace("[\x82\x91\x92]", "'", $text);

//Quotes: Replace straight apostrophes with smart apostrophes
preg_replace("\b'\b", "?", $text);

//Quotes: Replace straight double quotes with smart double quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace('\B"\b([^"\x84\x93\x94\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight double quotes with smart double quotes.
//Unicode version for use with Unicode regex engines.
preg_replace('\B"\b([^"\u201C\u201D\u201E\u201F\u2033\u2036\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight single quotes with smart single quotes.
//Unicode version for use with Unicode regex engines.
preg_replace("\B'\b([^'\u2018\u2019\u201A\u201B\u2032\u2035\r\n]+)\b'\B", "?\1?", $text);

//Quotes: Replace straight single quotes with smart single quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace("\B'\b([^'\x82\x91\x92\r\n]+)\b'\B", "?\1?", $text);

Escape

//Regex: Escape metacharacters
//Place a backslash in front of the regular expression metacharacters
preg_replace("[][{}()*+?.\\^$|]", "\\$0", $text);

Security

//Security: ASCII code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[\x00\x08\x0B\x0C\x0E-\x1F]'

//Security: ASCII code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'[\x00-\x1F]'

//Security: Escape quotes and backslashes
//E.g. escape user input before inserting it into a SQL statement
preg_replace("\\$0", "\\$0", $text);

//Security: Unicode code and unassigned characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Excludes tabs and line breaks.
'[^\P{C}\t\r\n]'

//Security: Unicode code and unassigned characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Includes tabs and line breaks.
'\p{C}'

//Security: Unicode code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[^\P{Cc}\t\r\n]'

//Security: Unicode code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'\p{Cc}'

SSN (Social security numbers)

//Social security number (US)
'\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b'

Trim

//Trim whitespace (including line breaks) at the end of the string
preg_replace("\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start and the end of the string
preg_replace("\A\s+|\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start of the string
preg_replace("\A\s+", "", $text);

//Trim whitespace at the end of each line
preg_replace("[ \t]+$", "", $text);

//Trim whitespace at the start and the end of each line
preg_replace("^[ \t]+|[ \t]+$", "", $text);

//Trim whitespace at the start of each line
preg_replace("^[ \t]+", "", $text);

URL's

//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into backreferenes 1 through 4
'\b((?#protocol)https?|ftp)://((?#domain)[-A-Z0-9.]+)((?#file)/[-A-Z0-9+&@#/%=~_|!:,.;]*)?((?#parameters)\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'

//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into named capturing groups.
//Works as it is with .NET, and after conversion by RegexBuddy on the Use page with Python, PHP/preg and PCRE.
'\b(?<protocol>https?|ftp)://(?<domain>[-A-Z0-9.]+)(?<file>/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(?<parameters>\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'

//URL: Find in full text
//The final character class makes sure that if an URL is part of some text, punctuation such as a
//comma or full stop after the URL is not interpreted as part of the URL.
'\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]'

//URL: Replace URLs with HTML links
preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', '<a href="\0">\0</a>', $text);

Words

//Words: Any word NOT matching a particular regex
//This regex will match all words that cannot be matched by %REGEX%.
//Explanation: Observe that the negative lookahead and the \w+ are repeated together.
//This makes sure we test that %REGEX% fails at EVERY position in the word, and not just at any particular position.
'\b(?:(?!%REGEX%)\w)+\b'

//Words: Delete repeated words
//Find any word that occurs twice or more in a row.
//Delete all occurrences except the first.
preg_replace('\b(\w+)(?:\s+\1\b)+', '\1', $text);

//Words: Near, any order
//Matches word1 and word2, or vice versa, separated by at least 1 and at most 3 words
'\b(?:word1(?:\W+\w+){1,3}\W+word2|word2(?:\W+\w+){1,3}\W+word1)\b'

//Words: Near, list
//Matches any pair of words out of the list word1, word2, word3, separated by at least 1 and at most 6 words
'\b(word1|word2|word3)(?:\W+\w+){1,6}\W+(word1|word2|word3)\b'

//Words: Near, ordered
//Matches word1 and word2, in that order, separated by at least 1 and at most 3 words
'\bword1(?:\W+\w+){1,3}\W+word2\b'

//Words: Repeated words
//Find any word that occurs twice or more in a row.
'\b(\w+)\s+\1\b'

//Words: Whole word
'\b%WORD%\b'

//Words: Whole word
//Match one of the words from the list
'\b(?:word1|word2|word3)\b'

//Words: Whole word at the end of a line
//Whitespace permitted after the word
'\b%WORD%\s*$'

//Words: Whole word at the end of a line
'\b%WORD%$'

//Words: Whole word at the start of a line
'^%WORD%\b'

//Words: Whole word at the start of a line
//Whitespace permitted before the word
'^\s*%WORD%\b'

1/9/09

Decorators with Zend_Form

LINK

Zend_Form has been lauded by many as a welcome addition to Zend Framework, and a flexible solution to the problem of forms. That said, one point of flexibility it offers has proved to be a pain point for many developers: decorators. This tutorial aims to shed some light on decorators, as well as provide strategies for creating your own decorators and combining them in creative ways to customize the output your forms generate.

How to use Zend_Log


Setup the logger in the Bootstrap file:
//initiate the logger - Log to a file
$writer = new Zend_Log_Writer_Stream($root.'\log\test.txt');
$logger = new Zend_Log($writer);
//Log to Database.
$columnMap = array('lvl' => 'priority', 'msg' => 'message', 'timestamp' => 'timestamp', 'lvlName' => 'priorityName');
$dbwriter = new Zend_Log_Writer_Db($db, 'log_table_name', $columnMap);
$logger->addWriter($dbwriter);
//Log to firebug
$writerFirebug = new Zend_Log_Writer_Firebug();
$writerFirebug->setPriorityStyle(6, 'TRACE');
$logger->addWriter($writerFirebug);
$registry->logger = $logger;

Using the logger:
$logger = Zend_Registry::get('logger');


Log an exception:
$exception = new Zend_Exception('Test exception');
$logger->err($exception);

Log a message:
$logger->info('Show Information about something');

1 comments:

steenvinkel said...

For filtering add following to the bootstrap file:
$filter = new Zend_Log_Filter_Priority(Zend_Log::INFO);
$logger->addFilter($filter);

This will make sure no debug messages are logged.

1/8/09

Code Sniffer

Asbtract:
PHP_CodeSniffer is a PHP5 script that tokenises and "sniffs" PHP and JavaScript code to detect violations of a defined coding standard. It is an essential development tool that ensures your code remains clean and consistent. It can also help prevent some common semantic errors made by developers.

Download:
http://pear.php.net/package/PHP_CodeSniffer/download

Install:
pear install PHP_CodeSniffer

Using:
phpcs /path/to/code/my_dir

Using TextMate with PHP_CodeSniffer.


Quick Start

1. Install PHP command line.
2. Install PHP_CodeSniffer PEAR package.
3. Download PHP_CodeSniffer command v0.1 from here.
4. Unzip the downloaded file.
5. Install the bundle by double clicking the icon.

Once the bundle is installed, you have to update two lines of code to make it work in your system.

One is the path to php executable file on the first line of the code. The typical location on OS X is /usr/bin/php.

interpreter path

Next, you need to change the path to PHP_CodeSniffer installation. In most of systems, ‘/usr/bin/phpcs’ would work just fine.

phpcs path

Now you are ready to go. Try to open your PHP code in TextMate, then the default setup will let you run the command by pressing ‘Shift + Apple Key + C’. It will display the output window like:

PHP_CodeSniffer Commands result


Introduction

I have been a PHP developer more than 2 years now and have been using JEdit as primary text editor until recently I switched to TextMate. Despite of excellent editing power and numerous great plugins, the slow nature of Java really put me down and has been consistently irritating. After several trials on various alternative text editors on mac, I ended up using TextMate that satisfies me good enough to give up good old JEdit.

During my daily coding duties, I use PHP_CodeSniffer (a.k.a phpcs) to validate my PHPcode against my company’s coding standards, typically on the command line using Terminal. Only the problem is that I have to type the path to the file name whenever I need update different files. It is not really efficient especially you are working on big project with many many files. Thankfully ‘Commands’ in TextMate gave me a nice nifty shortcut to run phpcs on without jumping to Terminal app.

One of the biggest advantage of using TextMate is Commands. It is a powerful tool that TextMate can have certain level of integration with external scripts. What phpcs_cmd does is simply to run PHP_CodeSniffer on your opened PHP source code, then displays the result in HTML format. The command itself is also written in PHP.

Using PHP_CodeSniffer

PHP_CodeSniffer is PEAR package that tokenises and “sniffs” PHP code to detect violations of a defined set of coding standards. It is an essential development tool that ensures that your code remains clean and consistent. It can even help prevent some common semantic errors made by developers. It is now used by PEAR community. Every PEAR code is checked by PHP_CodeSniffer everyday and reports the errors to developers.

You can find the documentation for more details on PEAR website or Greg Sherwood’s blog who is the maintainer of this package.

PHP với Simple XML lib

PHP - XML
1. The ExtensibleMarkup Language (XML): là ngôn ngữ đánh dấu với mục tiêu là đơn giản hóa
việc chia sẻ dữ liệu giữa các hệ thống khác nhau
Cú pháp XML cơ bản cho một phần tử là
<tên thuộc_tính="giá trị">nội dung</tên>
Cấu trúc XML đơn giản:
<?xml version="1.0"?>
<message>Hello, World!</message>
Ví dụ: Hãy tạo tệp tin XML có nội dung như sau:
Đây là tệp tin XML:
<?xml version="1.0" encoding="utf-8"?>
<library>
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen . Unwin</publisher>
</book>
<book isbn="0451524934">
<title>1984</title>
Title Author Publisher ISBN
TheMoon Is a HarshMistress R. A. Heinlein Orb 312863551
Fahrenheit 451 R. Bradbury Del Rey 345342968
The Silmarillion J.R.R. Tolkien G Allen & Unwin 48231398
1984 G. Orwell Signet 451524934
Frankenstein M. Shelley Bedford 031219126X<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
</library>
2. SimpleXML
• Parsing XML Documents
// Load an XML string
$xmlstr = file_get_contents(’library.xml’);
$library = simplexml_load_string($xmlstr);
hoặc dùng
// Load an XML file
$library = simplexml_load_file(’library.xml’);
• Truy cập Children and Attributes
<?php
// Load an XML string
$library = new SimpleXMLElement("library.xml", NULL, true);
foreach ($library->book as $book)
{
echo $book["isbn"] . "<br>";
echo $book->title . "<br>";
echo $book->author . "<br>";echo $book->publisher . "<br><br>";
}
?>
• Để hiển thị các thuộc tính và giá trị: dùng hàm SimpleXMLElement::children() và
SimpleXMLElement::attributes(), SimpleXMLElement::getName()
foreach ($library->children() as $child)
{
echo $child->getName() . ":\n";
// Get attributes of this element
foreach ($child->attributes() as $attr)
{
echo " " . $attr->getName() . ": " . $attr . "<br>";
}
// Get children
foreach ($child->children() as $subchild)
{
echo " " . $subchild->getName() . ": " . $subchild . "<br>";
}
echo "<br>";
3. XPath Queries: được dùng để lấy ra values của các Elements hay Attributes XPath đóng một
vai trò quan trọng trong việc trao đổi dữ liệu giữa các computers hay giữa các chương trình ứng
dụng vì nó cho phép ta lựa chọn hay sàng lọc ra những tin tức nào mình muốn để trao đổi hay
hiển thị.
$library = new SimpleXMLElement("library.xml", NULL, true);
$results = $library->xpath("/library/book/title");
foreach ($results as $title)
{
echo $title . "<br>";
}
// Search the first child element
$results = $library->book[0]->xpath("title");foreach ($results as $title)
{
echo $title . "<br>";
}
• Thay đổi tài liệu XML
$library = new SimpleXMLElement("library.xml", NULL, true);
$book = $library->addChild("book");
$book->addAttribute("isbn", "0812550706");
$book->addChild("title", "Ender's Game");
$book->addChild("author", "Orson Scott Card");
$book->addChild("publisher", "Tor Science Fiction");
header("Content-type: text/xml");
echo $library->asXML();
• Xóa một phần tử:
$library->book[0] = NULL;
• Làm việc với Namespaces:
<?xml version="1.0"?>
<library xmlns="http://example.org/library"
xmlns:meta="http://example.org/book-meta"
xmlns:pub="http://example.org/publisher"
xmlns:foo="http://example.org/foo">
<book meta:isbn="0345342968">
<title>Fahrenheit 451</title>
<author>Ray Bradbury</author>
<pub:publisher>Del Rey</pub:publisher>
</book>
</library>$namespaces = $library->getDocNamespaces();
foreach ($namespaces as $key => $value)
{
echo "{$key} => {$value}<br>";
}
Bài tập:
1. Tìm hiểu DOM
2. Tìm hiểu Drupal XML-RPC

1/7/09

Game nổi tiếng 1 thời

Ngày nay các em 9x tòan chơi các game đồ họa tiên tiến thế hệ mới, dung lượng từ 1 vài Gb đến cả chục GB :D. Nhớ hồi xưa mình xuất ngày ra hàng 4 nút chơi, sau đey thì mua máy về, cả ngày ngồi nhà chơi các trò contra, mario, songlong ếch, subasa nhật, bắn tăng sao mà vui thế :D.
Bây giờ kiếm lại đc 1 đống, + thêm 1 soft giả lập dùng đơn giản chỉ viec open là xong :D
soft giả lập nặng nhất có 800KB, game thi từ 30KB->200KB cao nhất. Ôn lại ngày xưa cũng vui ^__^.
Ko nói nhiều nữa mời mọi người download:
(host có thể hơi lag, nếu ko vô đc mọi người cứ save link đợi đêm or sáng down)

1.Đầu tiên soft giả lập 4nút:
Trích dẫn:
downn soft gia lap here
II) Game:
1. Game đầu tiên cưc kì nổi tiếng dương nhiên là mario 1 rùi :D
Trích dẫn:
DOWNLOAD: Down Here


2. Game típ Super Mario Bros 2 :D
Trích dẫn:
DOWNLOAD:DOWN HERE


3. Super Mario Bros 3
Trích dẫn:
DOWNLOAD: DOWN HERE


4. Game bắn tăng huyền thoai ^^
Trích dẫn:
DOWNLOAD: DOWN HERE


5. Song long ếch ( giống hệt của 6 nút :D)
Trích dẫn:
DOWNLOAD: DOWN HERE


6. Kinh điểm shooter: Contra :D
Trích dẫn:
DOWNLOAD: DOWN HERE


7. Bomber Man siêu khủng game đặt bom đó ah nhưng chỉ có 65KB :))
Trích dẫn:
DOWNLOAD: DOWN HERE


8. Siêu Bóng đá Subasa( game kinh điển)
Trích dẫn:
DOWNLOAD: DOWN HERE


9. Kunio Kun no Nekketsu Soccer League sút chuối, sút cá ...v.v :))
Trích dẫn:
DOWNLOAD: DOWN HERE