Reputation: 429
how can I delete everything that is behind an empty space. I have a date like: 10.10.2010 18:34 with an empty space between the year and the 18. I only need the first part of the string (only 10.10.2010). So I tried to use preg_replace to remove everything behind the empty space, but it doesnt work. How would my expression have to be?
Thank you for your help! phpheini
Upvotes: 1
Views: 300
Reputation: 4713
If you're confident of the formatting:
$date = strstr('10.10.2010 18:34', ' ', true); // requires PHP 5.3.0 or greater
Upvotes: 1
Reputation: 164723
Based on your simple requirements, rather than going with a full regex solution, you can simply tokenize the string using strtok()
$datePart = strtok($dateString, ' ');
Edit: The only reason I could see to involve regular expressions would be to validate the date-time string at the same time as extracting parts. For example
if (preg_match('/(\d{1,2}\.\d{1,2}\.\d{4}) (\d{1,2}:\d{2})/', $dateTimeString, $parts)) {
$date = $parts[1];
$time = $parts[2];
} else {
throw new Exception('Invalid date-time string format');
}
Upvotes: 3
Reputation: 490153
$str = '10.10.2010 18:34';
$str = preg_replace('/\s.*?$/', '', $str);
var_dump($str); // string(10) "10.10.2010"
As Phil Brown states, however, using something like strtok()
is much better for a simple task like this (compare the answers and it is obvious).
Upvotes: 0