Tag Archives: replace

Javascript: How to Extract a Number from a String Programming 04 JUL 2013

javascript logoIn my web development work, I’m quite fond of using the trick of generating grouped elements by making sure their IDs all share a common number with a bit of unique text.

So for example I could have a set of elements with the IDs accordionheading1, accordionpanel1, accordiontext1 and accordionheading2, accordionpanel2, accordiontext2. Now in order for this to be useful, I need to be able to extract the number from these strings so that I can automatically guess an element’s associated partners, meaning that you now know exactly what is coming next:

One of the easier ways of extracting a number from a string using javascript is by making use of a bit of regex, utilizing the digit negated shorthand character class \D to do our dirty work.

In practice:

var element = 'accordion24paneldrop';
id = element.replace( /\D+/g, '');
alert(id); //24

Nifty.

Check it else for yourself using JSFiddle! (JS Bin is pretty cool too)

And there Goes the Stove My Life 28 OCT 2011

Aargh, so frustrating! Finally after a year of building back up from the money lows reached during Chantelle’s unpaid maternity leave, finally when I have enough spare cash to splash out on either a dishwasher or a television for the braai room, the bloody stove goes and acts up again!

Our little Defy 600 STS Ther@fan and us certainly haven’t enjoyed a very harmonious 1st year together, and after spending more than enough money on it to keep it running over the period (well, to be fair, I think it was only twice), this latest little game it is playing with us by screwing with its dials is the final straw that broke this camel’s back!

So on Gumtree an advert has gone, and pleasingly enough we have already had some interest, so hopefully out it goes – I need the convenience of an always working oven, not one I have to keep hoping will work when I need it! :)

Anyway, Chantelle and I have already done a bit of shopping about for a replacement, and after much deliberation, it would seem that we’ve settled on a very nice little unit from Whirlpool, from Tafelberg Meubels for around R3,500 – could have gone for a cheaper KIC model, but we both decided that in the end, a therma fan oven is more useful than an oven without one of these heat spreading devices.

And besides, the little money we hope to make off the Defy should bring this down to under R3,000.

Of course, this also means a new hob as these units go hand in hand, but at least we get to keep the existing extractor fan… and our kitchen gets a shiny new look!

Still, I really, really could have done with that TV or dishwasher you know…

How to Stop LibreOffice Writer from Automatically replacing Simple Quotation marks with Curly Quotation marks CodeUnit 14 OCT 2011

While curly or smart quotation marks are perhaps more preferable when writing a novel or an official document, there is often a case for not automatically replacing your simple straight quotation marks (both single and double quotes) with these more fancy, curly quotation marks, like when you are including code in your text for example.

LibreOffice Writer by default does this replacement for you, but thankfully it at least makes it pretty simple to turn this feature off as well.

Simply access the main Tools menu, select the AutoCorrect options… and on the resulting dialog window, open the Localized Options tab.

There you will see sections detailing the replacement for both Single and Double quotes – simply uncheck the Replace box to turn off, or alternatively check the box to turn the autocorrect feature back on.

Easy as that! :)

MySQL: How to Remove all Newline Characters from a Column CodeUnit 29 JUN 2011

Annoyingly, carriage returns and line-feeds (aka newline characters) often get sucked up into our database through imports, inserts and the like, which is annoying because these generally invisible characters play havoc with simple WHERE COLUMN = STRING statements because what you thought were matching strings are actually not matching at all! However, a once off statement to remove all these annoying chr(10) and chr(13) characters is actually pretty simple to implement.

Using the handy REPLACE MySQL function and taking recognition that MySQL denotes character returns as r and line-feeds as n, we can put together a simply SQL statement that looks like this:

UPDATE `myTable` SET `myColumn` = REPLACE(REPLACE(`myColumn`, 'r', ''), 'n', '');

This will remove all character returns and line-feeds by replacing them with a blank string.

Nifty.

Rolling Back the Carpet My Life 11 JUN 2010

Whew. So Chantelle had Cliffie, the plumber/maintenance man they use at Gordon’s Beach Lodge come and have a look at the leaking geyser and it turns out that thankfully it wasn’t the geyser at fault at all! Instead, one of the copper pipes feeding into the geyser had corroded enough to from a small hole the size of a pinhead, causing a perpetual spray of water against the geyser at a rate fast enough to fill up a cup withing a minute.

This water then ran down the geyser and soaked into the cement below, basically spreading throughout the study and coming up to soak the underfelt of the carpet, making those big wet spots that had alerted us to the problem in the first place.

So after a bit of a hunt to find the water mains, Cliffie cut out the bit of offending pipe and welded in a replacement, meaning that the water leakage has now been stopped.

However, it isn’t all a field of daisies just yet.

Now because it is a pipe from the structure and not the geyser that caused the damage, responsibility for repairing it now falls to the complex management company, namely Micsam, which means that they are now liable for the costs. Already Chantelle has entertained some people to assess whether or not the carpet can simply be lifted and cleaned, but as the underfelt is already completely soaked and ruined, I’m afraid that the verdict is that the whole thing will have to be lifted up and replaced.

Fantastic.

Anyway, so now it falls to us to clear out the study, roll up the wet carpet and then allow the cement to dry out for a couple of days, before the team rolls in and fits in a replacement.

Sigh, and of course it is the perfect timining for drying out wet cement floors of course! :P

(On a side note, Olympus seems to love the exposed underside of the carpet. He runs up and takes a flying leap over the wet cement – refuses to walk on it – lands on the other side and proceeds to sharpen his claws on the underside. Perfect furry fun in other words!)

PHP Script to Trim and Replace Apostrophes for Each Value in Each Column of Each Table in a MySQL Database CodeUnit 31 MAY 2010

Annoyingly, I got saddled with a database for a system which contained a whole lot of “uncleaned data”, in other words data with a lot of trailing and leading, uncessary whitespace characters, as well as a generous helping of apostrophes and quotation marks – the cause of many a headache when working on a web-based application using PHP and MySQL.

Needless to say, inherent relationships and thus joins were failing left, right and center thanks to this badly formed data and as such I needed to quickly whip up a script that would strip all leading and trailing whitespace plus replace any apostrophes or quotation marks with their web code equivalent for each and every value that appeared in every row, column and table in the database.

And this is the little PHP script that did it for me:

//just to help prevent the script from timing out
ini_set('memory_limit', '100M');
ini_set('default_socket_timeout',600);
ini_set('max_input_time',600);
ini_set('max_execution_time',600);

//give us something to look at on the screen
echo "Start Process...";

//create a database connection
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'databaseName';
$conn = mysql_connect($mysql_hostname,$mysql_user,$mysql_password);
mysql_select_db($mysql_database, $conn);

//build up the list of tables to process
$sql = "SHOW TABLES";
$tables = array();
echo 'Building audit tables list...';
$tablestemp = $db->query($sql,2);
foreach ($tablestemp as $tabletemp)
{		
  $tables[] = $tabletemp;
}
echo 'Audit table list built.';

//run through each table, build up a column list and then run an update SQL statement against the column
foreach($tables as $table)
{
  set_time_limit(80);
	$sql = "SHOW COLUMNS FROM `$table`";
	$columns = array();
	echo 'Building audit columns list for ' . $table . '...';
	$columnstemp = $db->query($sql,2);
	foreach ($columnstemp as $columntemp)
	{		
			$columns[] = $columntemp;
	}
	echo 'Audit column list for ' . $table . ' built.';
	
	foreach($columns as $column)
	{
		set_time_limit(80);
		//trim and replace in one foul SQL swoop!
    $sql = "UPDATE `$table` SET `" . $column['Field'] . "` = TRIM(REPLACE(REPLACE(REPLACE(`" . $column['Field'] ."`,"'","'"),'"','"'),'~','''))";
    echo "$sql";
    mysql_query($sql);
	}
}
mysql_close($conn);
echo "End Process.";

And there you go, pretty handy little helper script to have in your possession when you are presented a database with some dirty data included inside! :)

PHP: How to Get all the Numbers out of an Alphanumeric String? CodeUnit 07 MAY 2010

Given a registration code, or something important like that, which often contains information encoded in the alphanumeric string itself, it is sometimes quite useful to be able to simply strip out the letters from the string, leaving only the numeric part behind.

So for example, for a code that looks like LTTCRA003 (my old University student number in case you were wondering), it might be of use to pull out the digit part as that information tells you how many times the LTTCRA hash of name and surname has occurred before.

Now in order to grab the numbers we are simply going to knock out all the letters contained in the string and for that we will use preg_replace, a function which makes use of regular expression matching to make its string replacements.

So what exactly do we need to do in terms of code then?

Well, the regular expression itself is pretty simple (probably the most simple you can get), and put into code, this is what will solve our little problem for us:

$numbers = preg_replace('/[a-zA-Z]/','','LTTCRA003');

The result of this code will be ‘003’, thanks to us replacing all the letters with blanks.

And there you go. That’s one way of getting all the numbers out of an alphanumeric string! :)

PHP: How to Get all the Letters out of an Alphanumeric String? CodeUnit 21 APR 2010

Given a registration code, or something important like that, which often contains information encoded in the alphanumeric string itself, it is sometimes quite useful to be able to simply strip out the numbers from the string, leaving only the letters behind.

So for example, for a code that looks like LTTCRA003 (my old University student number in case you were wondering), it might be of use to pull out the letter part as that information tells you what hash of my name and surname computes to.

Now in order to grab the letters we are simply going to knock out all the numbers contained in the string and for that we will use preg_replace, a function which makes use of regular expression matching to make its string replacements.

So what exactly do we need to do in terms of code then?

Well, the regular expression itself is pretty simple (probably the most simple you can get), and put into code, this is what will solve our little problem for us:

$letters = preg_replace('/[0-9]/','','LTTCRA003');

The result of this code will be ‘LTTCRA’, thanks to us replacing all the numbers with blanks.

And there you go. That’s one way of getting all the letters out of an alphanumeric string! :)