JDT |
John Dixon |
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:
In our case, we just want to change a non-breaking space to a normal space - simple ! Author: John Dixon Go back to PHP Tutorials home page Go back to Tutorials home page
|
|
|||||
|
© 2007-2009 - John Dixon Technology Ltd |
|||||