Posts in the “php” category

PHP: How to strip unwanted characters from a string

[toc]

PHP string FAQ: How can I strip unwanted characters from a PHP string? (Also asked as, How can I delete unwanted characters from a PHP string?)

Solution

Here’s a quick PHP preg_replace example that takes a given input string, and strips all the characters from the string other than letters (the lowercase letters "a-z", and the uppercase letters "A-Z"):

 

A MAMP new website setup tutorial

MAMP website setup FAQ: How do I configure MAMP and my Mac so I can develop a new PHP website? (Or, Can you share a Mac MAMP setup tutorial?)

Assuming you already have MAMP installed, creating a new MAMP website is pretty easy. I've gotten to the point where I can do it in about two minutes. You just have to configure your /etc/hosts file and your MAMP Apache configuration file. Here's how.

Creating a PHP date in the format for a SQL Timestamp insert

PHP date/time FAQ: How do I create a date in the proper format to insert a SQL Timestamp field into a SQL database?

First off, you may not need to create a date in PHP like this. If you're using plain old PHP and a database like MySQL, you can use the SQL 'now()' function to insert data into a SQL timestamp field, like this:

A Java CRUD generator example

I'm still spending a couple of hours a day working on my Java CRUD generator. Technically, because this is all driven by templates, this is also a PHP CRUD generator, and a Python CRUD generator, and in general a programming-language independent CRUD generator, but at the moment it seems easiest to refer to it as a "Java CRUD generator", so I'll call it that for the moment.

How my CRUD generator works

In today's update I'd like to show you how this works. In short, you start with a database table like this one:

PHP: How to remove non-printable characters from strings

PHP FAQ: How do I remove all non-printable characters from a string in PHP?

I don’t know of any built-in PHP functions to remove all non-printable characters from a string, so the solution is to use the preg_replace function with an appropriate regular expression.

Solution: Allow only ASCII characters

For my purposes I don’t have to work with Unicode characters, so one of the best solutions for my purposes is to strip all non-ASCII characters from the input string. That can be done with this preg_replace code:

$result = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);

That code removes any characters in the hex ranges 0-31 and 128-255, leaving only the hex characters 32-127 in the resulting string, which I call $result in this example.

You can see how this works in the interactive PHP shell. In this example I just want to get rid of the characters ‘ and ’, which don’t work well in my current application:

myprompt> php -a
Interactive shell

php > $string = "‘Hello,’ she said.";
php > $result = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
php > echo $result;
Hello, she said.

As you can see, the characters ‘ and ’ are not in the $result string.

Note: You can read more about hex and octal character sequences on this php.net page.

Also note that if you prefer octal characters to hexadecimal characters, this code should work as well:

$result = preg_replace('/[\000-\031\200-\377]/', '', $string);

I just tested that on my example and it worked fine, but I haven’t tested it with other strings. (This page is a good resource for basic octal and hex values.)

Possible solution: Use the 'print' regex

Another possible solution is to use the ‘print’ regular expression shown in this example with preg_replace:

$result = preg_replace('/[[:^print:]]/', "", $string);

Per the PHP regex doc, the [:print:] regex stands for “any printable character,” so for my example I thought it would leave the ‘ and ’ characters in the resulting string, but to my surprise the output looks like this:

php > $string = "‘Hello,’ she said.";
php > $result = preg_replace('/[[:^print:]]/', "", $string);
php > echo $result;
?Hello,? she said.

I don’t know why that regex ends up putting ? characters in the resulting string, so at the moment I’m calling this a “possible solution” rather than a solution. Note that if you just echo out the original string, it prints fine:

php > echo $string;
‘Hello,’ she said.

More solutions (Unicode)

As I mentioned, I don’t currently have to concern myself with Unicode characters, so the original ASCII character solution I showed works fine for me. If you do need to handle Unicode characters, this SO page shows a possible solution.

More PHP regular expressions

Finally, while I’m in the neighborhood, here’s a list of PHP “range” regular expressions from the php.net regex page. As the “range” name implies, these patterns can be used to match ranges of characters in PHP strings:

[:digit:]      Only the digits 0 to 9
[:alnum:]      Any alphanumeric character 0 to 9 OR A to Z or a to z.
[:alpha:]      Any alpha character A to Z or a to z.
[:blank:]      Space and TAB characters only.
[:xdigit:]     .
[:punct:]      Punctuation symbols . , " ' ? ! ; :
[:print:]      Any printable character.
[:space:]      Any space characters.
[:graph:]      .
[:upper:]      Any alpha character A to Z.
[:lower:]      Any alpha character a to z.
[:cntrl:]      .

As shown in my earlier example, you actually need to use two brackets with these regex patterns when using preg_replace:

$result = preg_replace('/[[:^print:]]/', "", $string);

Summary

In summary, if you wanted to see how to remove non-printable characters from strings in PHP, I hope these examples are helpful.

PHP write stderr - Write to STDERR in a PHP script

PHP STDERR FAQ - How do I write to STDERR in a PHP script, specifically a PHP command line script?

I've written a lot of my command line scripts in PHP lately, and I just ran across this problem in my own script, how to write to STDERR in PHP. Fortunately the solution is easy, just use the PHP fwrite function like this:

fwrite(STDERR, “hello, world\n”);

Or, in a more real-world example, here's how I'm writing MySQL error messages to STDERR in PHP:

A PHP “string to date” example

Summary: A PHP “string to date” conversion example.

For a recent PHP calendar project I needed to convert a given string into a 'date' I could work with more easily. In short, given a string date like this:

"2011/05/21"

I wanted to convert that to some type of PHP date data structure I could use to render a calendar.

PHP string to date source code

The following PHP code shows the two steps I used to convert a date string into a PHP date structure I could work with:

Comments in PHP: PHP comment syntax and examples

It's funny, when I first started working with PHP, the first thing I wanted to know is "What is the PHP comments syntax?" (It reminds me of learning to ride a motorcycle, where the first thing you want/need to learn is how to stop.)

Fortunately, if you have a Unix/Linux and/or C programming background, the PHP comment syntax will seem very familiar, and I'll share some simple PHP comment examples here.

How to use PHP curl and curl_setopt with JSON web services

Here are two PHP scripts I just wrote that use curl and curl_setopt. The first example makes a GET request, and the second example makes a POST request, and passes JSON data to the web service it accesses.

A PHP curl GET request

This first one makes an HTTP GET request and prints the data that is returned by the URL that it hits:

CakePHP log output (Where is it?)

CakePHP log file output FAQ: Help, where is my CakePHP log output? I can't find my CakePHP error log output or my CakePHP debug log output.

If you're writing CakePHP log file output as shown in either of these two methods:

CakeLog::write('debug', 'Where is this message going?');
$this->log($this->data, 'debug');

but can't find this CakePHP log output in your Apache log files or PHP log files, fear not, it's somewhere else. That location is:

The PHP Base64 encode and decode functions

PHP FAQ: Can you share an example of the PHP Base64 encode and decode functions?

Every once in a while when you're working on a web application you'll run into data that can cause you some problems, and when that happens, the PHP base64_encode function can come to your rescue. Here's a quick look at a problem I ran into yesterday using CakePHP, and how the PHP base64_encode and base64_decode functions helped me encode a URL (URI) and bail me out of my predicament.

A CakePHP user registration form example

CakePHP user registration FAQ: The cookbook covers the topic of CakePHP user login forms, but the CakePHP Auth module uses SHA1 for passwords, and the cookbook doesn't cover user registration (creating users, and SHA1 passwords); how do I set up a CakePHP user registration form, including all necessary CakePHP model, view, and controller classes?

Setting up a basic CakePHP registration form isn't too hard, er, well, once you know how to do it. Here's how.

The Twitter API, PHP, and OAuth

Just a quick note today on how to access the Twitter API using PHP, specifically using the Abraham Williams PHP TwitterOAuth library. While the library itself seems very good, I couldn't find much in the way of documentation, particularly a simple "getting started" tutorial, so I thought I'd share this code.

In short, I dug through the PHP files in the root directory of the TwitterOAuth library, eventually creating this simple PHP Twitter client example:

PHP warning - Unable to load dynamic library ./apc.so (Solution)

While installing the PHP APC opcode cache, I just ran into the following error:

PHP Warning:  PHP Startup: Unable to load dynamic library './apc.so' - ./apc.so: 
cannot open shared object file: No such file or directory in Unknown on line 0

I found this error message in my PHP error log, but depending on your configuration I think it may also be in your Apache error log file.