I have the following bit of text (or some similar variation of it):
Recurring Event
First start: 2010-09-16 17:00:00 EDT
Duration: 4800
Event Status: confirmed
I need to select the timestamp of the "First Start" field and the duration.
Normally I would split the string at the colons, but since the timestamp contains them, it sort of becomes problematic. I'm not so good with regular expressions, but does anyone know one that will be able to select the two bits of data I need?
cheers,
Mike
Assuming the format stays this way you can search for ": ", i.e. a colon followed by a space. The string following this would be your data.
For a simple non-regex solution, find the first : with strpos($input, ":"), then the rest of the line will have the value.
$content = '
Recurring Event
First start: 2010-09-16 17:00:00 EDT
Duration: 4800
Event Status: confirmed
';
$contentArray = explode('EDT' , $content);
$head = trim($content[0]);
//$head will contain 'Recurring Event First start:2010-09-16 17:00:00 '
$headArray = explode(' ' , $head);
$timeStamp = trim(end($headArray)); //which will have 17:00:00
You can do:
if(preg_match('/First start: ([-\d :]+)/',$input,$m)) {
$timeStamp = trim($m[1]);
}else{
$timeStamp = '';
}
if(preg_match('/Duration: (\d+)/',$input,$m)) {
$duration = $m[1];
}else{
$duration = '';
}
Related
My string is given below.
$str = 'Hi $name. This is a reminder of your appointment at $dateformat("h:i A") on $dateformat("M d,Y").';
Suppose date is (coming from DB),
$appoinmentDate = '2019-02-02'
Now, I want to do following things with string
replace $name with John(name is coming from DB)
replace $dateformat("h:i A") with 08:52 AM (time is coming from DB)
$dateformat("M d,Y") should be replace with date("M d,Y",$appoinmentDate) and its result
should be Feb 02,2019 Like this
Important thing: $dateformat("h:i A") and $dateformat("M d,Y") will be dynamic it can be any possible date format
Can any one please help me to find out the solution?
You could use a regular expression that parses $str looking for any word starting with a $, and possibly followed by a ("...") sequence.
If there is a parentheses sequence, take all between the "" and use this as date format in a DateTime->format() call.
Finally, do 1 sprintf() with all the replacements and date/time insertions done at runtime
EDIT
Try this testscript :
<?php
//creating test string
$teststr='Hi $name. This is a reminder of your appointment at $dateformat("h:i A") on $dateformat("M d,Y").' ;
// parse all date format matches
$regex= "/[\$]dateformat\(?\"?([^\"]*)\"\)/" ;
$DTmatches=Array();
// try to match all $dateformat() occurences
if (preg_match_all($regex, $teststr, $DTmatches) )
{
echo sprintf("Found following matches: %s \r\n", print_r($DTmatches,true));
// replace this with your DB timestamp
$theDT = new DateTime("now", new DateTimeZone("UTC")) ;
// count the occurences
$nofOccurences = count($DTmatches[0]) ;
// run over each occurence
for ($i=0; $i < $nofOccurences; $i++)
$teststr = str_replace( $DTmatches[0][$i], $theDT->format($DTmatches[1][$i]), $teststr ) ;
}
else
echo "no dateformat() found" ;
echo sprintf("Replaced test string is: %s \r\n", $teststr) ;
?>
$copy_date = 'Hi test. This is a reminder of your appointment at $dateformat("h:i A") on $dateformat("M d,Y").';
$str = preg_replace('/\$dateformat\(\"h:i A\"\)/', date("h:i A"), $copy_date);
$str1 = preg_replace('/\$dateformat\(\"...../', "", $str);
$str2 = preg_replace('/\"\)/', "'Your Date'", $str1);
In the above code you can replace first date with date format and in other you can set date or text instead of Your date.
If you want to replace both data then remove date("h:i A").
I have a .txt file that has lines of text (bible verses) that include the date. I want to be able to display the text on our website, so that it shows the correct reading for that day and updates every day. Here is an example of the text:
Monday, December 28 — Psalm 148:1–6 Zechariah 10,11; Revelation
20:1–10
The Lord our God we will serve, and him we will obey. Joshua 24:24
Be steadfast, immovable, always excelling in the work of the Lord,
because you know that in the Lord your labor is not in vain. 1
Corinthians 15:58
Tireless Creator, often we succumb to post-celebration doldrums. We
lose our enthusiasm for service and witness. Help us remember that
even in the dullness of daily routine we can share your grace.
Rekindle the coals of our hearts with the fire of your love. Amen.
Tuesday, December 29 — Psalm 148:7–14 Zechariah 12–13:6; Revelation
20:11–21:8
God gives wisdom to the wise and knowledge to those who have
understanding. Daniel 2:21
Do not be foolish, but understand what the will of the Lord is.
Ephesians 5:17
It is difficult to discern your will, God of Wisdom. The Scriptures
inform us, but interpretations can be controversial, even adversarial.
Forgive our allowance of such disagreements to obstruct the work of
your Spirit in us. Show us how to live the way, the truth, and the
life of sacrificial love. Amen.
Any help you could offer would be greatly appreciated - I'm a code hobbyist, so it's probably best to treat me as a novice, if that helps. Thank you!
this is the kind of php code I've been playing with:
<?php // script.php
$searchfor = $_GET['january'];
$file = '2016 Daily Texts no hymns mac.txt';
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/$pattern/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:<br />";
echo implode("<br />", $matches[0]);
}
else{
echo "No matches found";
fclose ($file);
}
?>
So long as the date format is always consistent throughout the text
eg. Monday, December 28
your webpage will be able to extract a new verse for each day without any issue:
<?php
$today = date('l, F j');
$today_as_unix_timestamp = strtotime($today);
$tomorrow_as_unix_timestamp = ($today_as_unix_timestamp + (60 * 60 * 24));
$tomorrow = date('l, F j',$tomorrow_as_unix_timestamp);
$verses = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/2016_Daily_Texts_no_hymns_mac.txt');
$start = (strpos($verses,$today) + strlen($today));
$end = (strpos($verses,$tomorrow));
$verse_for_today = substr($verses,$start,($end - $start));
echo '<p>'.$verse_for_today.'</p>';
?>
you can use php to read the text file
<body>
<pre>
<?php
$myfile = fopen("text.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>
</pre>
I need a PHP script to loop through all .html files in a directory and in each one find the first instance of a long date (i.e. August 25th, 2014) and then adds a tag with that date in short format (i.e. <p class="date">08/25/14</p>).
Has anyone done something like this before? I'm guessing you'd explode the string and use a complex case statement to convert the month names and days to regular numbers and then implode using /.
But I'm having trouble figuring out the regular expression to use for finding the first long date.
Any help or advice would be greatly appreciated!
Here's how I'd do it in semi-pseudo-code...
Loop through all the files using whatever floats your boat (glob() is an obvious choice)
Load the HTML file into a DOMDocument, eg
$doc = new DOMDocument();
$doc->loadHTMLFile($filePath);
Get the body text as a string
$body = $doc->getElementsByTagName('body');
$bodyText = $body->item(0)->textContent; // assuming there's at least one body tag
Find your date string via this regex
preg_match('/(January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}(st|nd|rd|th)?, \d{4}/', $bodyText, $matches);
Load this into a DateTime object and produce a short date string
$dt = DateTime::createFromFormat('F jS, Y', $matches[0]);
$shortDate = $dt->format('m/d/y');
Create a <p> DOMElement with the $shortDate text content, insert it into the DOMDocument where you want and write back to the file using $doc->saveHTMLFile($filePath)
I incorporated the helpful response above into what I already had and it seems to work. I'm sure it's far from ideal but it still serves my purpose. Maybe it might be helpful to others:
<?php
$dir = "archive";
$a = scandir($dir);
$a = array_diff($a, array(".", ".."));
foreach ($a as $value) {
echo '</br>File name is: ' . $value . "<br><br>";
$contents = file_get_contents("archive/".$value);
if (preg_match('/(January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}(st|nd|rd|th)?, \d{4}/', $contents, $matches)) {
echo 'the date found is: ' . $matches[0] . "<br><br>";
$dt = DateTime::createFromFormat('F jS, Y', $matches[0]);
$shortDate = $dt->format('m/d/y');
$dateTag = "\n" . '<p class="date">' . $shortDate . '</p>';
$filename ="archive/".$value;
$file = fopen($filename, "a+");
fwrite($file, $dateTag);
fclose($file);
echo 'Date tag added<br><br>';
} else {
echo "ERROR: No date found<br><br>";
}
}
?>
The code assumes the files to modify are in a directory called "archive" that resides in the same directory as the script.
Needed the two different preg_match lines because I found out some dates are listed with the ordinal suffix (i.e. August 24th, 2005) and some are not (i.e. August 24, 2005). Couldn't quite puzzle out exactly how to get a single preg_match that handles both.
EDIT: replaced double preg_match with single one using \d{1,2}(st|nd|rd|th)? as suggested.
I am using following PHP code
<?
$data = file_get_contents('http://www.kitco.com/texten/texten.html');
preg_match_all('/([A-Z]{3,5}\s+[0-9]{1,2},[0-9]{4}\s+([0-9.NA]{2,10}\s+){1,7})/si',$data,$result);
$records = array();
foreach($result[1] as $date) {
$temp = preg_split('/\s+/',$date);
$index = array_shift($temp);
$index.= array_shift($temp);
$records[$index] = implode(',',$temp);
}
print_R($records);
?>
To READ the following data
--------------------------------------------------------------------------------
London Fix GOLD SILVER PLATINUM PALLADIUM
AM PM AM PM AM PM
--------------------------------------------------------------------------------
Jun 03,2013 1396.75 1402.50 22.4300 1466.00 1487.00 749.00 755.00
May 31,2013 1410.25 1394.50 22.5700 1471.00 1459.00 755.00 744.00
--------------------------------------------------------------------------------
What i want to do is Read GOLD ( BID & ASK ) price from below table, can anyone help in the regular expression changes?
New York Spot Price
MARKET IS CLOSED
Will open in
----------------------------------------------------------------------
Metals Bid Ask Change Low High
----------------------------------------------------------------------
Gold 1411.20 1412.20 +22.90 +1.65% 1390.10 1418.00
Silver 22.74 22.84 +0.48 +2.13% 22.26 23.08
Platinum 1495.00 1501.00 +41.00 +2.82% 1470.00 1511.00
Palladium 756.00 761.00 +7.00 +0.93% 750.00 766.00
----------------------------------------------------------------------
Last Update on Jun 03, 2013 at 17:14.58
----------------------------------------------------------------------
I'm not sure you could modify your existing regex to match both tables easily, but if you had the second table in a string, you could use:
$string = "PLAIN TEXT TABLE DATA HERE";
preg_match('/Gold\s+(\d+\.\d{2})\s+(\d+\.\d{2})/',$string,$matches);
$goldBid = $matches[1];
$goldAsk = $matches[2];
Here I'm only matching the numbers and period character. This code should return the numbers you're looking for. It uses your data string from your example.
<?
preg_match_all('!Gold\s+([0-9.]+)\s+([0-9.]+)!i',$data,$matches);
//New York
$ny_bid = $matches[1][0];
$ny_ask = $matches[2][0];
print("NY\nbid: $ny_bid\n");
print("ask: $ny_ask\n\n");
//Asia
$asia_bid = $matches[1][1];
$asia_ask = $matches[2][1];
print("Asia\nbid: $asia_bid\n");
print("ask: $asia_ask\n");
?>
Output
NY
bid: 1411.20
ask: 1412.20
Asia
bid: 1406.80
ask: 1407.80
You can also use T-Regx library
<?php
pattern('Gold\s+([0-9.]+)\s+([0-9.]+)', 'i')->match($data)->forEach(function ($m) {
print 'bid: ' . $m->group(1);
print 'ask: ' . $m->group(2);
});
I'm creating a PDF file from a txt-template with tcpdf ([Example 8][1]). The txt-template looks like this:
SALUTATION
FIRSTNAME LASTNAME
STREET CURRENTDATE
SOMEMOREINFORMATION MYWEBSITE
I replace those markers with the correct value. So that it would look like this:
Mr.
John Doe
Downingstreet 10 14th May, 2010
john#doe.com www.stackoverflow.com
In this example, when I replace the values, the indention of the date is dependent on the length of the street name (which I don't want). I could solve this issue with str_pad but the problem is, I normally use three columns and there are lines which only have content in col1 and col3 as in the last line. How can I solve that problem? Is there something like the "overwrite" function in Word, that when you write, the text just gets overwritten?
Thanks in advance.
Count street's string length and then add/remove left padding of date.
You can use sprintf, e.g.
function something($street, $currentDate, $foo) {
$s = sprintf('%-20s %-18s %s',
$street,
$currentDate,
$foo
);
return $s;
}
echo something('streetA', '14th May, 2010', 'lalala'), "\n";
echo something('Downingstreet 10', '14th May, 2010', 'lalala'), "\n";
echo something('abcdefghijklmnopqrstuvwxyz 10', '14th May, 2010', 'lalala'), "\n";
prints
streetA 14th May, 2010 lalala
Downingstreet 10 14th May, 2010 lalala
abcdefghijklmnopqrstuvwxyz 10 14th May, 2010 lalala
(as you can see from the third line the width specification is the minimum length, so you might have to use something like substr())
I presume you are just str_replace()'ing the placeholders with their values?
$streetPlaceHolder = 'STREET ';
$streetReplacement = str_pad('Downingstreet 10', strlen($streetPlaceHolder));
$template = str_replace($streetPlaceHolder, $streetReplacement, $template);
Presumably you will run into the same problem with SOMEMOREINFORMATION. This same solution can be used.
I realize you said str_pad was not an ideal solution for you. However, I do not understand why, even if you extend this to three columns. You can still get by with this method.