Bruno Bruno - 2 months ago 6
PHP Question

Strip dates in string using PHP

Suppose I have a string like this:

# Training 2016-10-04 (06:00-08:00) fred # Training 2016-10-04 (08:00-10:00) (Radio)


How can I strip all the dates from this string using str_replace? I tried the following:

$datepattern = '(\d+)-(\d+)-(\d+)';
$finalstring = str_replace($datepattern, '', $finalstring);


Any instance of a date with that format should be removed, how can I go about this?

Answer

Use preg_replace() and use proper regex which is:

$finalstring = '# Training 2016-10-04 (06:00-08:00) fred # Training 2016-10-04 (08:00-10:00) (Radio';
$datepattern = '/(\d+)-(\d+)-(\d+)/';
$finalstring = preg_replace($datepattern, '', $finalstring);
echo $finalstring;