我试图通过找到第二个句点然后是空格来优化preg_match_all
:
<?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.
答案 0 :(得分: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.
答案 1 :(得分: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()
。
答案 2 :(得分: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_all
? preg_match
就足够了。
答案 3 :(得分:0)
我不认为(。\ s {2})意味着你的意思。就目前而言,它将匹配“。”(一段时间后跟两个空格),而不是“。”的第二次出现。
答案 4 :(得分: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);
答案 5 :(得分: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.