2

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"?

1
  • have you tried replacing the expires with an empty string and putting it through strtotime? Commented Dec 21, 2012 at 23:25

3 Answers 3

5
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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Yeah, I have to put 14 because somehow the space turns into nbsp in the browser when I make it 9.
1

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);

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.