Jump to content

preg_match -- removing some characters?


extrovertive

Recommended Posts

Asssumging the following output for date:

Date: Wed, 24 Dec 2008 01:52:41 GMT

$dateA = get_headers("http://www.yahoo.com");
$date = $dateA[1];
preg_match('/[^(date)]+/i', $date, $newdate);
echo $newdate[0];

 

Now, I just want a regex to remove "Date:" and just display

Wed, 24 Dec 2008 01:52:41 GMT

 

How come above is not working?

Link to comment
Share on other sites

$str = 'Date: Wed, 24 Dec 2008 01:52:41 GMT';
$str = preg_replace('#Date: (.+)#', '$1', $str);
echo $str;

 

Output:

Wed, 24 Dec 2008 01:52:41 GMT

 

The reason why your solution wasn't working is because you are using a negative character class to exclude for (date) which means, find any of the following characters: ( or d or a or t or e or ) characters one or more times.. But this is not what you want, as one or more of those characters may appear in the rest of the string. One way is to use brackets for capturing.. so if you look at what I did, I said, find Date: , then capture the rest, and repace the string with what was captured (which was everything except Date: ).

 

EDIT - You can use preg_match if you don't want to modify the initial string:

preg_match('#Date: (.+)#', $str, $match);
echo $match[1];

 

This all only works based on the assumption that your sample string is all that is in it (no extra sftuff surrounding it).

Link to comment
Share on other sites

FYI, as of PHP 6, functions like split() will be removed from the core and made into extensions (a la ereg POSIX). As well, the manual seems to endorse preg_split above split:

 

"preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split()."

 

So if you want to future-proof your code...probably best to not use split().

 

 

Link to comment
Share on other sites

then how about just explode().

 

Yep, that would work too (probably better than preg_match in this case):

$str = 'Date: Wed, 24 Dec 2008 01:52:41 GMT';
$arr = explode("Date: ", $str);
echo $arr[1];

 

My point was that using split() is not really recommended anymore it seems.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.