Match hyphen character from a string to make an array output - php

I have a string that should contain a name and a date of registration:
Dipak Misra - 18 Nov 2018 10:20
I want to convert this string into array like this:
Array ( [0] => Dipak Misra [1] => 18 Nov 2018 [2] => 10:20 )
I am using preg_match_all() function:
$re = '/\w+(?:[-\s]\w+)*/';
$str = "Dipak Misra - 18 Nov 2018 10:20";
preg_match_all($re, $str, $matches);
print_r($matches[0]);
I am getting output Like this:
Array ( [0] => Dipak Misra [1] => 18 Nov 2018 10 [2] => 20 )
Please guide me.

If the format of that string does not change, you could split on either a space, hyphen space, or split on a space where on the left and the right side a digit is present instead of matching.
- |(?<=\d) (?=\d)
Regex demo
For example:
print_r(preg_split("/ - |(?<=\d) (?=\d)/", "Dipak Misra - 18 Nov 2018 10:20"));
Result:
Array
(
[0] => Dipak Misra
[1] => 18 Nov 2018
[2] => 10:20
)

Use preg_match() with ([^-]+)\s+-\s+(.*)\s(\d+:\d+) as pattern instead
$re = '/([^-]+)\s+-\s+(.*)\s(\d+:\d+)/';
$str = "Dipak Misra - 18 Nov 2018 10:20";
preg_match($re, $str, $matches);
unset($matches[0]);
print_r($matches);
Check result in demo

$pattern = "/(\w+\s\w+)\s-\s([0-9]{2}\s\w+\s[0-9]{4})\s([0-9]+:[0-9]+)/";
$chain = "Dipak Misra - 18 Nov 2018 10:20";
preg_match_all($pattern, $chain, $matches);
$data = [
'chain' => $chain,
'pattern' => $pattern,
'name' => $matches[1],
'date' => $matches[2],
'time' => $matches[3]
];
echo "<pre>";
print_r($data);
echo "<pre>";
the output

Related

regex: show all phone numbers

i want to see all phone numbers in my string. right now it has only one number in the array 'match' how can i get all the numbers in my array?
$str = "djvdsfhis 0647382938 rdfrgfdg tel:0647382938 rfgdfgfd 06 47 38 29
38 fdgdfrggfd tel:06-47382938 cxgvfdgsfdc";
$arr = '~\d{2}-\d{8}|\d{10}~';
$success = preg_match($arr, $str, $match);
if ($success) {
echo "Match: ".$match[0]."<br />";
print_r($match);
}
i get this as output:
djvdsfhis ffgfg 0647382938 rdfrgfdg tel:0647382938 rfgdfgfd 06 47 38 29 38 fdgdfrggfd tel:06-47382938 cxgvfdgsfdc
Match: 0647382938
Array ( [0] => 0647382938 )
but i want to have my array like this:
Array ( [0] => 0647382938 [1] => 0647382938 [2] => 06-47382938
You should use preg_match_all. Which will output an array of all of the results of your regex, in this instance an array of the numbers.
$str = "djvdsfhis 0647382938 rdfrgfdg tel:0647382938 rfgdfgfd 06 47 38 29
38 fdgdfrggfd tel:06-47382938 cxgvfdgsfdc";
$arr = '~\d{2}-\d{8}|\d{10}~';
$success = preg_match_all($arr, $str, $match);
if ($success) {
print_r($match);
}
Test it here :
http://sandbox.onlinephpfunctions.com/code/350d10b1be46ce3a5851d7671750bac28f9110f0
You can also use T-Regx tool which has automatic delimiters:
pattern('\d{2}-?\d{8}')->match($str)->all();

Splitting a single string to an array on more than one delimiter

Is it possible to explode the following:
08 1.2/3(1(1)2.1-1
to an array of {08, 1, 2, 3, 1, 1, 2, 1, 1}?
I tried using preg_split("/ (\s|\.|\-|\(|\)) /g", '08 1.2/3(1(1)2.1-1') but it returned nothing. I tried checking my regex here and it matched well. What am I missing here?
You should use a character class containing all the delimiters which you want to use for splitting. Regex character classes appear inside [...]:
<?php
$keywords = preg_split("/[\s,\/().-]+/", '08 1.2/3(1(1)2.1-1');
print_r($keywords);
Result:
Array ( [0] => 08 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 1 [6] => 2 [7] => 1 [8] => 1 )
You can use preg_match_all():
$str = '08 1.2/3(1(1)2.1-1';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

how to extract parts of the string

I have the following string in PHP.
"File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124"
I need to fetch file, date, and size separately.
What is the best way to extract the required values?
explode() OR substring()
Explode requires some common value, substring requires start and end. In both cases i am a bit confuse.
Any help would be greatly appreciated.
Try this:
<?php
$text = "File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124";
$pattern = '/file:(.*?)date:(.*?)size:(.*)/i';
preg_match($pattern, $text, $out);
print_r($out);
?>
Output:
Array
(
[0] => File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124
[1] => content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpg
[2] => Fri Mar 18 11:30:17 CET 2016
[3] => 23124
)
Demo: https://3v4l.org/OcSXH

Use RegEx to get (parsed) times from string

I need some direction on how to alter my current RegEx line.
Example string:
9:00 AM - 9:30 AM
Desired output:
900 930 (each can be an index in an array or whatever)..
Current approach:
preg_match('/^([0-9]{1,2}):([0-9]{1,2}) ?([ap]m)/i', trim($presentationtime), $matches);
however this only seems to get me the FIRST (stripped/parsed) time.
results:
$presentationtime = $matches[1] . $matches[2];
echo 'Matches check: '. $matches[0] . '<br>';
echo 'Matches check: '. $matches[1] . '<br>';
returns:
Matches check: 9
Matches check: 00
How can I alter my regex to get BOTH times (stripped/parsed the same way)..
I'm expecting a 6 index array..but can only get a 3 index/count array
as #anubhava says use preg_match_all
$presentationtime = '9:00 AM - 9:30 AM';
preg_match_all('/([0-9]{1,2}):([0-9]{1,2}) /', trim($presentationtime), $matches);
print_r($matches);
results:
Array
(
[0] => Array
(
[0] => 9:00
[1] => 9:30
)
[1] => Array
(
[0] => 9
[1] => 9
)
[2] => Array
(
[0] => 00
[1] => 30
)
)
Edit to answer the comment:
very lazy workaround to get one dimensional array, banal regex
$presentationtime = '9:00 AM - 9:30 PM';
preg_match('/([0-9]{1,2}):([0-9]{1,2})\s([apm]+)\s-\s([0-9]{1,2}):([0-9]{1,2})\s([apm]+)/i', trim($presentationtime), $matches);
result
Array
(
[0] => 9:00 AM - 9:30 PM
[1] => 9
[2] => 00
[3] => AM
[4] => 9
[5] => 30
[6] => PM
)
You have to simply use preg_match_all (as stated by anubhava in the comment) and remove the ^ at the start of the regex:
preg_match_all('/([0-9]{1,2}):([0-9]{1,2}) ?([ap]m)/i', trim($presentationtime), $matches);
Then $matches will be like:
Array
(
[0] => Array
(
[0] => 9:00 AM
[1] => 9:30 AM
)
[1] => Array
(
[0] => 9
[1] => 9
)
[2] => Array
(
[0] => 00
[1] => 30
)
[3] => Array
(
[0] => AM
[1] => AM
)
)
If you want to refine the regex you may use:
preg_match('/([0-9]{1,2}):([0-5]\d)\s*([ap]m)/i', trim($presentationtime), $matches);
The minute section is will match 2 digits from 00 to 59, the space section \s* is optional and matches more than one whitespace char (space, tab, CR, FF...)
One way of doing that:
$data = '9:00 AM - 9:30 AM';
print str_replace('-', ' ', preg_replace("/[^0-9-]/","", $data));
Result:
900 930
keep digits and dash
replace dash with space
In the previous example, I was using limited regex with preg_replace. To keep things simple and using time with AM/PM, I'd just explode (as you already thought about),
$data = '9:00 AM - 9:30 PM';
$timeArray = array_map('trim', explode('-', $data)); // trim each array item
$timeArray = array_map('Time24Hr', $timeArray); // clean up time
print_r($timeArray);
function Time24Hr($time) {
$time_ampm = explode(' ', $time);
if (strtolower(trim($time_ampm[1])) === 'am') {
// A
return $time_ampm[0];
// B
//return str_replace(':', '', $time_ampm[0]);
// C
//return $time;
}
$hr_min = explode(':', trim($time_ampm[0]));
// A
return ($hr_min[0] + 12) . ':' . $hr_min[1];
// B
//return ($hr_min[0] + 12) . $hr_min[1];
// C
//return ($hr_min[0] + 12) . ':' . $hr_min[1]. ' ' . $time_ampm[1];
}
Results:
Result A:
Array
(
[0] => 9:00
[1] => 21:30
)
Result B:
Array
(
[0] => 900
[1] => 2130
)
Result C: -- obviously this is insane, but you can easily make it sane. This is just an example
Array
(
[0] => 9:00 AM
[1] => 21:30 PM
)
Of course, this simplistic method can be streamlined much further. This method doesn't need regex.

Find date after a particular word

I would like to find the date in a string after a particular word (key).
My string is dynamic and the date format also not same from one string to another string.
$data = "Balance- 0.30,Val-Aug 29 2013, Free Bal- 0.00";
or
$data = "Bal: 96.27.Valid Sep 26 2013.Toll Free Dial 578785";
or
$data = "BalanceRs.0.00,Expiry date: Apr 04 20141 Live Scores";
or
$data = "Your current balance is 0.20.Your account expires on 2013-11-23 23:59:59.";
or
$data = "Main Bal Rs.87.850 Val 09-07-2014,More";
$key = array('Val-','Val','Valid','Expiry date:','expires on');
$result=preg_match_all("/(?<=(".$key."))(\s\w*)/i",$data,$networkID);
$myanswer = #$networkID[0][0];
Here I am getting the output of only the first word.
Anyone please guide me to get the date. Thanks.
How about:
$data = "Balance- 0.30,Val-Aug 29 2013, Free Bal- 0.00";
$data .= "Bal: 96.27.Valid Sep 26 2013.Toll Free Dial 578785";
$data .= "BalanceRs.0.00,Expiry date: Apr 04 20141 Live Scores";
$data .= "Your current balance is 0.20.Your account expires on 2013-11-23 23:59:59.";
$data .= "Main Bal Rs.87.850 Val 09-07-2014,More";
$key = array('Valid','Val-','Val','Expiry date:','expires on');
$key_str = implode('|', $key);
preg_match_all("/(?<=$key_str)\s*((?:\w{3} \d\d \d{4})|(?:\d{4}-\d\d-\d\d)|(?:\d\d-\d\d-\d{4}))/i", $data, $networkID);
print_r($networkID);
output:
Array
(
[0] => Array
(
[0] => Aug 29 2013
[1] => Sep 26 2013
[2] => Apr 04 2014
[3] => 2013-11-23
[4] => 09-07-2014
)
[1] => Array
(
[0] => Aug 29 2013
[1] => Sep 26 2013
[2] => Apr 04 2014
[3] => 2013-11-23
[4] => 09-07-2014
)
)

Categories