3

preg_match_allピリオドとスペースの 2 番目の出現を見つけて、a を絞り込もうとしています。

<?php

$str = "East Winds 20 knots. Gusts to 25 knots. Waters a moderate chop.  Slight chance of showers.";

preg_match_all ('/(^)((.|\n)+?)(\.\s{2})/',$str, $matches);

$dataarray=$matches[2];
foreach ($dataarray as $value)
{ echo $value; }
?>

しかし、それは機能しません{2}。発生が正しくありません。

preg_match_all動的HTMLをスクレイピングしているため、使用する必要があります。

文字列からこれをキャプチャしたい:

East Winds 20 knots. Gusts to 25 knots.
4

6 に答える 6

2

ここに別のアプローチがあります

$str = "East Winds 20 knots. Gusts to 25 knots. Waters a moderate chop.  Slight chance of showers.";


$sentences = preg_split('/\.\s/', $str);

$firstTwoSentences = $sentences[0] . '. ' . $sentences[1] . '.';


echo $firstTwoSentences; // East Winds 20 knots. Gusts to 25 knots.
于 2010-03-25T04:40:41.757 に答える
1

すべてのピリオドを取得してからスペースを取得し、結果の一部のみを使用しないのはなぜですか?

preg_match_all('!\. !', $str, $matches);
echo $matches[0][1]; // second match

ただし、これから何をキャプチャしたいのか正確にはわかりません。あなたの質問は少し漠然としています。

ここで、2 番目のピリオド (その後にスペースが続く) までのすべてをキャプチャする場合は、次を試してください。

preg_match_all('!^((?:.*?\. ){2})!s', $str, $matches);

貪欲でないワイルドカード マッチを使用するDOTALLため、.改行にマッチします。

最後のスペースをキャプチャしたくない場合は、それも実行できます。

preg_match_all('!^((?:.*?\.(?= )){2})!s', $str, $matches);

また、文字列の終端をカウントできるようにすることもできます。これは、次のいずれかを意味します。

preg_match_all('!^((?:.*?\.(?: |\z)){2})!s', $str, $matches);

また

preg_match_all('!^((?:.*?\.(?= |\z)){2})!s', $str, $matches);

preg_match()最後に、1 つのマッチを終えて最初のマッチが必要な場合は、この目的ではなく簡単に使用できますpreg_match_all()

于 2010-03-25T04:35:43.530 に答える
0

正規表現は必要ありません。シンプルに考える

$str = "East Winds 20 knots. Gusts to 25 knots. Waters a moderate chop.  Slight chance of showers.";
$s = explode(". ",$str);
$s = implode(". ",array_slice($s,0,2)) ;
print_r($s);
于 2010-03-25T05:11:50.517 に答える
0

ひもからこれをキャプチャしたい: 東風 20 ノット. 突風25ノット。

2 つの提案があります。

1) 文字列を "." (ダブル スペース) で展開し、結果を出力するだけです。

$arr = explode(".  ",$str);
echo $arr[0] . ".";
// Output: East Winds 20 knots. Gusts to 25 knots.

2) Preg_match_all よりもパフォーマンスに適した Explode と Strpos を使用します。

foreach( explode(".",$str) as $key=>$val) {
    echo (strpos($val,"knots")>0) ? trim($val) . ". " : "";
}
// Output: East Winds 20 knots. Gusts to 25 knots.
于 2010-06-24T05:51:35.883 に答える
0

あなたが試すことができます:

<?php
$str = "East Winds 20 knots. Gusts to 25 knots. Waters a moderate chop.  Slight chance of showers.";
if(preg_match_all ('/(.*?\. .*?\. )/',$str, $matches))
    $dataarrray = $matches[1];
var_dump($dataarrray);
?>

出力:

array(1) {
  [0]=>
  string(40) "East Winds 20 knots. Gusts to 25 knots. "
}

また、1 つのオカレンスだけをキャプチャしたい場合、なぜ ? を使用しているのpreg_match_allですか? preg_match十分なはずです。

于 2010-03-25T04:39:53.677 に答える
0

(.\s{2}) は、あなたが考えていることを意味しているとは思いません。このままでは、"." (ピリオドの後に 2 つのスペースが続く) に一致し、"." の 2 回目の出現には一致しません。

于 2010-03-25T04:40:28.010 に答える