JDT

 

John Dixon
Technology
Limited

 
Google

Using Regular Expressions with PHP


Although Perl is undoubtedly the language of choice when it comes to working with regular expressions, there are times when you might need to use them to clean up variables, for example, within your PHP scripts.

I needed to do this recently when I had to process a load of variables, the contents of which had been derived from a database table. The problem was that the variables contained HTML tags and non-breaking spaces.

Here is the bit of PHP code I used to clean up each variable:

// Get rid of HTML tags
$text = strip_tags($text);

// Get rid of non-breaking spaces
$pattern = '/ /';
$replacement = ' ';
$text = preg_replace($pattern, $replacement, $text);

OK, the first bit of the code, the bit that gets rid of the HTML tags, isn't actually a regular expression - it uses the PHP strip_tags function. I thought I would leave this is in though because it is a really useful function for getting rid of HTML tags from a string.

Incidentally, if you wanted to clear all the tags except, say the <h1> and <a> tags, you could use:

strip_tags($text, '<h1><a>');

The second part of the code, the bit that gets rid of the non-breaking spaces, is the regular expression. The code, I think, is pretty straight forward:

  1. You set the pattern you want to search for.
  2. You set the replacement for that pattern.
  3. You run the regular expression.

In our case, we just want to change a non-breaking space to a normal space - simple !


Author: John Dixon
John Dixon Technology Ltd







Go back to PHP Tutorials home page

Go back to Tutorials home page



Earnings Tracker is John Dixon Technology's FREE open source accounting / bookkeeping software tool.

Aimed at UK contractor and freelancers, Earnings Tracker enables you to perform many bookkeeping and accounting tasks, helping you to keep track of your company's earnings and outgoings.

The software is written in PHP and MySQL and is available to use for FREE online, or as a FREE download.

As it is written in open source software, you are free to modify the code yourself, enabling you to produce a customized version of Earnings Tracker that fits your own specification.

Earnings Tracker can also be used simply as a dividend, corporation tax, or VAT calculator.

Need free accounting software
 


JDT

© 2007-2009 - John Dixon Technology Ltd

Privacy Statement

Terms & Conditions