Jump to content

[SOLVED] Changing 8 2009 to just 8


HoTDaWg

Recommended Posts

hi there

 

i get a feeling this is a really stupid question and i apologize for not trying harder to figure it out, i just cant get my head around it and my deadline is slowly winding down.

 

im trying to replace a string such as "8 2009" (or "12 2009") to just "8" here is what i have been experimenting with, but i cant seem to get it right:

<?php
$thatmonth = "8 2009";
preg_replace('/^[\d]+[\s\d]+$/','/^[\d]+$/',$thatmonth)
?>

 

any help would be greatly appreciated, thanks

 

HoTDaWg

Link to comment
https://forums.phpfreaks.com/topic/170776-solved-changing-8-2009-to-just-8/
Share on other sites

If that is your entire string you can simply use string indexes.

 

$thatmonth = "8 2009";
echo $thatmonth[0];

 

That would work on single digit months... but in the event of double digits, you would have to know that there are two digits and echo out the first two indexes... based on the same assumptions (that the string only consists the format of month[space]year), sscanf comes to mind on this one for me:

 

$thatmonth = "12 2009";
sscanf($thatmonth, '%d', $month);
echo $month; // 12

What are string indexes? I've worked with them in Python, but I didn't know they existed in PHP

 

Well, a string is a series of charactes of which are stored in indexes..

 

Example:

$str = 'cat';
echo $str[0] . "<br />\n"; // output: c
echo $str[1] . "<br />\n"; // output: a
echo $str[2] . "<br />\n"; // output: t

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.