Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active December 17, 2015 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RadGH/5556804 to your computer and use it in GitHub Desktop.
Save RadGH/5556804 to your computer and use it in GitHub Desktop.
Convert parts of a string to date components, noted by a percent sign (%)
<?php
/* ----------------------------
Parse a string with percent-signed wildcards, where the wildcards are PHP date characters.
Example:
$string = "Today is %F %j%S"
Returns: Today is January 1st
*/
function parse_date($string, $date = false) {
if ( !$date ) $date = time();
// Get an array of all matches
// The string of random letters are all PHP Date() characters
preg_match_all('/\%[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/', $string, $all_matches);
// Look 2-deep for matches
foreach( (array) $all_matches as $local_match) {
foreach( (array) $local_match as $match) {
$char = str_replace('%', '', $match); // Remove % symbol
$val = date($char, $date); // Convert date character to date value
// Update our string, replacing the first occurence
$string = preg_replace( "/{$match}/", $val, $string, 1);
}
}
return $string;
}
@RadGH
Copy link
Author

RadGH commented May 10, 2013

<?php
$var = "Today is %F %j%S";

$the_date = parse_date($var);

print_r($the_date);

// Output:
// Today is May 10th

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment