Forum Moderators: coopster
I am dealing with some large text files that contain lots of wine tasting notes. I am trying to come up with a clever construct that will enable me to shift a word in a line to the beginning of the line based on a regex that will identify a year. This is what I've come up with and it seems to work, however, I'm sure there's a better way. Any ideas..?
$string = 'Latour Pauillac 1995 Bordeaux';
$wine = explode(' ', $string);for ($i = 0; $i < count($wine); $i++)
{
if (preg_match('#\d{4}#', $wine[$i]))
{
echo $wine[$i] . ' ';
}
}
for ($i = 0; $i < count($wine); $i++)
{
echo preg_replace('#\d{4}#', '', $wine[$i]) . ' ';
}
echo $wine[2] . ' ' . $wine[0] . ' ' . $wine[1] . ' ' . $wine[3];
would also work. The problem is that the text strings are formatted differently. In some strings the year will be the second element, in other it'll be the third, and so on...
$string = 'Latour Pauillac 1995 Bordeaux';
print preg_replace("/(.*)\s?(\d{4})\s?(.*)/", "$2 $1 $3", $string);
If you wanted to be sure you only matched four numbers by themselves, you might use the boundary flag:
$string = 'Latour Pauillac 1995 Bordeaux';
print preg_replace("/(.*)\s?(\b\d{4}\b)\s?(.*)/", "$2 $1 $3", $string);
Hope this helps.
Justin