Osman
Osman

Reputation: 1771

How to get 1 character before a specified character

My string "**7:00am-4:00pm** M-F" What I am trying to do is extract the "7" and the "4", but those numbers can be different from string to string. I have looked up may functions that can find the occurrences of ":" but they either return the beginning half, only match the first occurrence, or return true or false.

Upvotes: 2

Views: 83

Answers (4)

user1329212
user1329212

Reputation:

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.

Upvotes: 1

Chris Gutierrez
Chris Gutierrez

Reputation: 4755

preg_match_all('/([0-9]+):/', '**7:00am-4:00pm** M-F', $matches); 
$numbers = end($matches); 
$start = $numbers[0];
$end = $numbers[1];

Upvotes: 1

sberry
sberry

Reputation: 132018

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.

Upvotes: 3

Peter Gluck
Peter Gluck

Reputation: 8236

Use strpos() and subtract 1:

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

if ($index > 0) {
  $value = substr($test, $index - 1, 1);
}

Upvotes: -2

Related Questions