2

私の文字列"**7:00am-4:00pm** M-F" 私がやろうとしているのは と を抽出することですが"7""4"これらの数字は文字列ごとに異なる場合があります。の出現を見つけることができる多くの関数を調べましたが":" 、それらは最初の半分を返すか、最初の出現のみに一致するか、true または false を返します。

4

4 に答える 4

3

Seems like a good case for regular expressions. Here is one that should do the trick:

<?php 

function get_times($str) {
    preg_match('#\*\*(\d{1,2}):\d\d\w+-(\d{1,2}):\d\d\w+\*\*#', $str, $matches);
    return array($matches[1], $matches[2]);
}

$strs = array();
$strs[] = "**7:00am-4:00pm** M-F";
$strs[] = "**11:00am-1:00pm** M-F";
$strs[] = "**4:00am-11:00pm** M-F";
$strs[] = "**11:00am-11:00pm** M-F";

foreach ($strs as $str) {
    echo $str . "\n";
    list($start, $end) = get_times($str);
    echo "Start: $start, End: $end\n\n";
}

OUTPUT

**7:00am-4:00pm** M-F
Start: 7, End: 4

**11:00am-1:00pm** M-F
Start: 11, End: 1

**4:00am-11:00pm** M-F
Start: 4, End: 11

**11:00am-11:00pm** M-F
Start: 11, End: 11

NOTE
This will work for times with 1 or 2 digits as shown in the example.

于 2012-08-30T22:31:26.813 に答える
1
preg_match_all('/([0-9]+):/', '**7:00am-4:00pm** M-F', $matches); 
$numbers = end($matches); 
$start = $numbers[0];
$end = $numbers[1];
于 2012-08-30T22:41:20.630 に答える
1

You can use explode function

$string = "**7:00am-4:00pm** M-F";

$string = explode(":",$string);

$first  = preg_replace("/[^0-9]/","", substr($string[0],-2));
$second = preg_replace("/[^0-9]/","", substr($string[1],-2));

And it works double digits times.

于 2012-08-30T22:31:46.903 に答える
-2

Use strpos() and subtract 1:

$index = strpos($text, ":");

if ($index > 0) {
  $value = substr($test, $index - 1, 1);
}
于 2012-08-30T22:31:12.210 に答える