0

I need to get everything before "On Sun, May 27, 2012 at 6:25 AM,"

I am hoping to get everything before "On xxx, xxx xx, xxxx at xx:xx xx,"

The problem here is that May, 27, and 6 are all variable in length. What is the best tool for this job. Due to my lack of experience with regex I am trying to use explode() but it doesn't appear it can do the job here. Is regex my best option?

[EDIT]

I ended up using a combination of answers. I went with:

preg_match("/(.*)On\s+(Sun|Sat|Fri|Thu|Wed|Tue|Mon),\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d?\d,\s+\d{4}\s+at\s+\d?\d:\d\d\s+[AP]M,/i", $to, $end);

4

3 に答える 3

2

このようなものだと思います:

/On\s+(Sun|Sat|Fri|Thu|Wed|Tue|Mon),\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d?\d,\s+\d{4}\s+at\s+\d?\d:\d\d\s+[AP]M,/i

[編集]

コメントによると: 大文字と小文字を区別しないサポートを追加しました (i正規表現の末尾に修飾子を追加することにより)。また、式のスペースを変更して空白文字を許可し、単語間に複数のスペースを許可するよう\sに追加しました。+

質問では、月名の長さが可変であると指定されていましたが、曜日名が可変であると指定されていなかったため、長い曜日名または短い月名をサポートするように変更していません。ただし、必要に応じてこれらのバリアントを追加するのは簡単です。

[編集]

$to = "Let me know how this response looks..... On Sun, May 27, 2012 at 6:25 AM, Pr";
preg_match("/On\s+(Sun|Sat|Fri|Thu|Wed|Tue|Mon),\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d?\d,\s+\d{4}\s+at\s+\d?\d:\d\d\s+[AP]M,/i", $to, $end);

このコードは、コメントに記載されている例で機能します。

それが役立つことを願っています。

于 2012-05-27T14:35:23.993 に答える
1
preg_match('/(.*?) On \w+, \w+ \d?\d, \d+ at \d?\d:\d?\d \w\w,/', 'grab this text here On Sun, May 27, 2012 at 6:25 AM,', $matches);
echo $matches[1];
// echoes 'grab this text here'

(.*?)先頭のすべてに\w+一致、任意の英数字に 1 回以上\d?\d一致、1 桁または 2 桁に一致

于 2012-05-27T14:40:32.777 に答える
0

正規表現は、パターンに基づいてデータを選択するために作成されたものであるため、機能します。ただし、',' (カンマ) で爆発させて、最初の 4 つの要素を再びまとめて文を形成することもできます。この場合、正規表現を使用した方が高速になるとは思えません。

最終的には、どちらが読みやすく、理解しやすいかは、あなたの好みです。この特定のケースで正規表現が持つ主な利点は、特定の値/パターンを抽出できることです。そのため、たとえば月を簡単に確保できます。

$dateString = "On Sun, May 27, 2012 at 6:25 AM, some other text here";

// using explode/implode
$result = explode(',',$dateString);

print "we got: " . implode(',', array_slice($result,0,3)) . "\n";

// using regular expression
$pattern = "/On [A-Z,a-z]{3}, [A-Z,a-z]{3} [0-9]+, [0-9]{4} at [0-9,:]+ (?:A|P)M/U";

preg_match($pattern,$dateString,$match);

print "We got: " . $match[0] . "\n";

PHP マニュアルの正規表現のサブセクションも最初のチュートリアルと一緒に読んでください。

個人的には、この場合、正規表現は視覚的にもパフォーマンス的にもやり過ぎかもしれないと思います。ただし、正規表現を学ぶと、非常に役立つ場合があります。

于 2012-05-27T14:52:37.277 に答える