3

我试图preg_match_all通过找到第二次出现的句点然后是空格来优化 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

但是,我不确定您到底想从中捕获什么。你的问题有点含糊。

现在,如果您想捕获直到并包括第二个周期(后跟一个空格)的所有内容,请尝试:

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()而不是preg_match_all()为此。

于 2010-03-25T04:35:43.530 回答
0

我想从字符串中捕捉到这一点:东风 20 节。阵风至 25 节。

我有两个建议:

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. "
}

此外,如果您只想捕获一次事件,为什么要使用preg_match_allpreg_match应该足够了。

于 2010-03-25T04:39:53.677 回答
0

我不认为 (.\s{2}) 意味着你认为它的意思。就目前而言,它将匹配“.”(句点后跟两个空格),而不是“.”的第二次出现

于 2010-03-25T04:40:28.010 回答
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 回答