无法用 preg_replace 替换其他符号来删除空格

Cannot remove whitespace with preg_replace with replacing other symbols

我有一个日期格式 YYYY-MM-DD HH-MM-SS 作为来自我的数据库的字符串

我想要做的是删除破折号和其他连字符和空格。

我已经在下面试过了;

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

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

这根本不起作用。我已经通过下面的方法解决了这个问题

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

我认为这不是一个好方法,所以我如何才能在删除其他符号(例如 -/: 的同时删除空格?使用 preg_replace?

提前致谢。

你可以试试这个:

[-, \/:]

Explanation

PHP样本

<?php

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

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

echo $result;


?>

如果您只想保留数字,请使用 \D - 不是数字

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

如果您想要保留月份名称的月份使用 \W - 不是字母(字母是字母、数字和'_')

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