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
https://forums.phpfreaks.com/topic/138265-preg_match-removing-some-characters/
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).

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?

 

Just split the string and put a limit on the split.

$string = "Date: Wed, 24 Dec 2008 01:52:41 GMT";
$a = split(" ",$string,2);
print "What i want is $a[1]\n";

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().

 

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.