2017-05-21 7 views
1

でコンテキストを取得し、私の最初のアプローチは、この正規表現です:はい私は検索文字列のコンテキストを取得したい正規表現

The fox is jumping in the gardenのために働く

!\.(.{20,})' . $string . '(.{20,})\.! 

。鳥は風の中を飛んでいる。彼が幸せになると、狐は庭に飛び込んできています。しかし、それはすべての話ではありません。

しかし

のために鳥が風に飛んでいません。彼が幸せになると、狐は庭に飛び込んできています。しかし、それはすべての話ではありません。

最初のドットがないためです。だから私は文字列の始まりであるドットか何かが必要です。

しかし、私はまだ彼が満足しているとき、キツネが庭にジャンプさ

に問題を持っているでしょう。しかし、それはすべての話ではありません。

はいと

かさえも。彼が幸せになると、狐は庭に飛び込んできています。しかし、それはすべての話ではありません。

私は可能な限り多くのコンテンツを持ちたいと思います(正に、60文字は20より良いでしょう)。しかし、私はまた、それ以上の文字がないときに動作するようにしたい。それをどうすれば実現できますか?

https://regex101.com/r/P3sFTw/1

編集:申し訳ありませんが、私はいつもコンテキストとして完全な文章を持っているしたいと、言っているはずです。つまり、左右の最小60文字(存在する場合)ですが、文章をカットしないで60文字を次のドット(または文字列の先頭)に拡張します。

+0

はあなたがそれぞれの文章のために欲しいものを示してもらえますか? – Toto

答えて

0
$testArray = [ 
    'Yes. The bird is flying in the wind. The fox is jumping in the garden when he is happy. But that is not the whole story.' => '...The fox is jumping in the <strong>garden</strong> when he is happy. But that...', 
    'The bird is flying in the wind. The fox is jumping in the garden when he is happy. But that is not the whole story.'  => '...The fox is jumping in the <strong>garden</strong> when he is happy. But that...', 
    'The fox is jumping in the garden when he is happy. But that is not the whole story.'          => '...is jumping in the <strong>garden</strong> when he is happy...', 
    'Yes. The fox is jumping in the garden when he is happy. But that is not the whole story.'         => '...fox is jumping in the <strong>garden</strong> when he is happy...', 
    'Yes. The fox is jumping in the garden when he is happy. But that is not the whole story of the garden story.'    => '...The fox is jumping in the <strong>garden</strong> when he is happy. But...', 
]; 

- >ここでいくつかのテスト結果:) via via ..."extractText()"

$searchString = 'garden'; 
foreach ($testArray as $testString => $testExpected) { 
    $stringy = S::create($testString); 
    $result = $stringy->extractText($searchString) 
        ->replace($searchString, '<strong>' . $searchString . '</strong>') 
        ->toString(); 
    self::assertSame($testExpected, $result, 'tested: ' . $testString); 
} 

- >https://github.com/voku/Stringy/

0

EDIT:質問の明確化の後、ここでは(私はあなたが使用することを適応させることができると確信していた後、あなたは何をしているうまくいけばです代わりに、変数):例に

[^.]*.{0,20}The fox is jumping in the garden.{0,20}.*?(?:\.|$) 

リンク:

https://regex101.com/r/P3sFTw/5

ORIGINAL:あなたは、次の正規表現を使用することができます。例に

(.{0,20})The fox is jumping in the garden(.{0,20}) 

リンク:

https://regex101.com/r/P3sFTw/3

+0

私は十分に指摘していないので、私は説明を更新しました。両者に完全な文章が必要です。 – Asara

+0

あなたの要件を満たすべきである新しいバージョンを追加しました。 – BenShelton

0

だから私はドットORの始まりである何かが必要になります文字列。

この1つは仕事をしていません:

!(?:^|\.)(.{20,})' . $string . '(.{20,})\.! 
+0

ありがとう、それはただ1つの小さな問題でした:) – Asara

+0

@Asara:まあ、完全な問題は何ですか?あなたの質問を編集し、期待した結果のテストケースを追加してください。 – Toto

関連する問題