Lunatic Fnatic Lunatic Fnatic - 1 month ago 16
PHP Question

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.

Answer

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;


?>