Lunatic Fnatic
Lunatic Fnatic

Reputation: 681

Cannot remove whitespace with preg_replace with replacing other symbols

I have a date format YYYY-MM-DD HH-MM-SS as a string from my database

What I want to do is to remove dashes and other hypens and whitepaces.

I have tried this below;

$date = preg_replace('/\s+-|:/', null, $row['acctstarttime']);

//also tried this
$date = preg_replace('/\s+-|:/', '', $row['acctstarttime']);

This does not work at all. I have solved it by using this below

$date = str_replace(' ', '', preg_replace('/-|:/', null, $row['acctstarttime']));

I don't think that is a good way to do it, so how could I remove spaces while removing other symbols such as -,/,: within only using preg_replace?

Thanks in advance.

Upvotes: 1

Views: 222

Answers (2)

Michael Piankov
Michael Piankov

Reputation: 1997

If you want to remain only numbers use \D - is not a number

str_replace(' ', '', preg_replace('\D', null, $row['acctstarttime']));

if months you want to preserve month names use \W - is not a letter(letters is letters, number and '_')

str_replace(' ', '', preg_replace('\D', null, $row['acctstarttime']));

Upvotes: 2

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can just try this:

[-, \/:]

Explanation

PHP Sample

<?php

$re = '/[-, \/:]/';
$str = '2000-11-11 12-12-13';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo $result;


?>

Upvotes: 0

Related Questions