phpheini
phpheini

Reputation: 429

How to remove everything behind the empty space?

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

Answers (3)

AdamJonR
AdamJonR

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

Phil
Phil

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

alex
alex

Reputation: 490153

$str = '10.10.2010 18:34';

$str = preg_replace('/\s.*?$/', '', $str);

var_dump($str); // string(10) "10.10.2010"

CodePad.

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

Related Questions