I need some help with a formatting function. I need to be able to take the input (function argument) and format the string to something else. Here's my options:
7am7pm
10am10pm
OFF
So, depending on what is selected, I want the regex to meet the following output criteria:
7am-7pm开发者_如何学C
10am-10pm
OFF
In other words, I need a hyphen inserted between the times and the original could be either [0-9]{2}
or [0-9]{1}
, so I'm guessing something like [0-9]{1,2}
, but I'm unsure how to create the function and use it in PHP.
Try
preg_replace("/(\d{1,2}(am|pm))(\d{1,2}(am|pm))/", "$1-$3", $string);
Demo: http://codepad.org/BBwW4eEE
Here's a version using assertions, so it only has to inject one character:
return preg_replace('/(?<=[a-z])(?=\d)/', "-", $arg);
It looks only for the position in the string where a letter ?<=
precedes and a number ?=
follows.
This should handle the times for you (and you'd manage "OFF" with a simple if statement):
$output = preg_replace('/^([0-9]{1,2}(am|pm))-?([0-9]{1,2}(am|pm))$/i', '$1-$3', $input);
How about this:
function format_date($date)
{
if( $date == 'off' ) return 'off';
return preg_replace( '/^(\d{1,2}\w{2})(\d{1,2}\w{2})$/' , '${1}-${2}' , $date );
}
I'm presuming you're saying the input will look like the first box, and should be formatted like the second?
精彩评论