Reputation: 1949
I know there's a lot of questions about this but it seems there's no simple way to do what I want. Take the following strings as an example:
expires Friday, December 21, 2012 @ 11:59pm ET
expires Saturday, December 22, 2012 @ 9:59pm ET
Both strings are similar but the following code is inconsistent:
echo substr($string, 14, 27);
as it outputs the following:
Friday, December 21, 2012 @
Saturday, December 21, 2012
Clearly, I don't want to keep the @ symbol. Is there a way to simply keep the date while removing "expires " and " @ ##:##pm ET"?
Upvotes: 2
Views: 7691
Reputation: 191749
preg_replace('/expires\s*(.*?)@/', '\1', $string);
You also don't really need to use a regex, but I would since it looks simpler. Here is a non-regex solution:
//I took 14 from you, but it seems to be 9
substr($string, 14, strpos($string, '@') - strlen($string));
Upvotes: 5
Reputation: 1416
I have to format the exact same string on a site i work on. this is what i use. seems to work okay:
<?PHP
function FormatDate($string)
{
$exploded = explode(" ", $string);
$newstring = $exploded['2']." ".$exploded['3']." ".$exploded['4']." ".$exploded['5'];
return $newstring;
}
echo FormatDate('expires Friday, December 21, 2012 @ 11:59pm ET');
Upvotes: 0
Reputation: 1343
You want to look at http://php.net/manual/wn/function.strpos.php
strpos "Find the position of the first occurrence of a substring in a string"
So you want to do something like this:
$string = "expires Friday, December 21, 2012 @ 11:59pm ET";
$string = str_replace("expires ", "", $string); //remove "expires "
$string = substr($string, 0, strpos($string, "@")-1); // Copy anthing up to the first "@"
echo($string);
Upvotes: 1