Archive

Posts Tagged ‘regex’

Using sed to search and replace contents of next line in a file.

January 24th, 2012 2 comments

This example will show you how easy it is using sed to find a particular line in a file and replace all or part of the next line. In this example, using htaccess we want to deny access to all clients except a particular dynamic IP (for your home connection for instance).

Your .htaccess file might look like this:

order deny,allow
deny from all

# allow from example.dyndns.org
allow from 8.8.4.4

And your sed code to update the allowed IP address might look like this:

sed -i -r "/# allow from example.dyndns.org/I{\
n; s/([0-9]{1,3}.){3}[0-9]{1,3}/8.8.8.8/\
}" .htaccess

Let’s look at it piece by piece.

  • /# allow from example.dyndns.org/I will search the file for this string. The I flag at the end makes the search case insensitive.
  • n; will tell sed to continue processing on the next line.
  • s/([0-9]{1,3}\.){3}[0-9]{1,3}/8.8.8.8/ will regex search for an IP and replace the match with your updated IP (in this case 8.8.8.8).
  • .htaccess is of course the input file to process.

Note that in .htaccess files, comments must be on a line of their own. End of line or inline comments are not permitted. In cases where you do not need to replace a part of the next line but rather all of it, our replacement becomes s/.*/8.8.8.8/

Categories: All, Linux

Masking fixed length strings in PHP.

May 17th, 2011 2 comments

A particular problem came up in the office today, masking of credit card numbers. As my friend Leonid has pointed out, one would think that this is a very simple task for any programmer. Or not.

Having read Leonid’s solution, and finding a comment on php.net which would also mask everything but the first and last four digits of a credit card number, I still felt that I needed to throw something of my own together. So here it is:

<?php
/**
 * Mask part of a string
 *
 * <code>
 * echo maskString('4012888888881881', 6, 4, '*');
 * </code>
 *
 * @param	string	$s		String to process
 * @param	integer	$start	Number of characters to leave at start of string
 * @param	integer	$end	Number of characters to leave at end of string
 * @param	string	$char	Character to mask string with
 * @return	string
 */
function maskString($s, $start, $end, $char = 'X') {
	$middle = '';
	for ($i = 0; $i < strlen($s) - $start - $end; $i++) {
		$middle .= $char;
	}
	return preg_replace('/^(d{' . $start . '})(d+.)(d{' . $end . '})$/', '${1}' . $middle . '${3}', $s);
}
?>