2017-11-21 11 views
3

私の文字列はHTMLドキュメントです。直前に句読点がない場合、HTMLの終了タグの前にドットを追加したい。句読点は.,?!:です。私はそのためにpreg_replaceを使いたいと思います。閉じるHTMLタグの前に紛れた句読点を追加する

<p>Today, not only we have so many breeds that are trained this and that.</p> 

<h4><strong>We must add a dot after the closing strong</strong></h4> 

<p>Hunting with your dog is a blah blah with each other.</p> 

<h2>No need to change this one!</h2> 

<p>Hunting with your dog is a blah blah with each other.</p> 

My機能:

$source = 'the above html'; 
$source = addMissingPunctuation($source); 

echo $source; 

function addMissingPunctuation($input) { 

    $tags = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ]; 

    foreach ($tags as $tag) { 

     $input = preg_replace(
      "/[^,.;!?](<\/".$tag.">)/mi", 
      ".${0}", 
      $input 
     ); 

    } 

    return $input; 
} 

私は.${0}.$0.${1}.$1.\\0.\\1を試してみましたが、何も働きません。最高でも、それは試合を呑み込むが、それを何かに置き換えない。私のパターンのマッチング部分はregex101や他のサイトで動作するようです。

所望の結果は次のとおりです。あなたがそのような$tagsを反復処理する必要はありません

<p>Today, not only we have so many breeds that are trained this and that.</p> 

<h4><strong>We must add a dot after the closing strong</strong>.</h4> 

<p>Hunting with your dog is a blah blah with each other.</p> 

<h2>No need to change this one!</h2> 

<p>Hunting with your dog is a blah blah with each other.</p> 
+0

それは、クリスの仕事あなたは答えとしてそれを置く場合、私はそれをマークすることができます... ...それが理由を理解するために多くは、しばらくの間、私の頭を悩まれて感謝を分析しますソリューションとして – Lazhar

答えて

2

、私は|implodeを行う、または可能なすべての要素のため、この場合のちょうど右のルールだろうどちらか。

$source = '<p>Today, not only we have so many breeds that are trained this and that.</p> 

<h4><strong>We must add a dot after the closing strong</strong></h4> 

<p>Hunting with your dog is a blah blah with each other.</p> 

<h2>No need to change this one!</h2> 

<p>Hunting with your dog is a blah blah with each other.</p>'; 
$source = addMissingPunctuation($source); 
echo $source; 
function addMissingPunctuation($input) { 
    return preg_replace("/[^,.;!?]\K<\/h[1-6]>/mi", ".$0", $input); 
} 

デモ:https://3v4l.org/6dNV7

ます。また、これまでの文字が要素の前にあったものを無視する必要がある、\Kはそれを行います。 ${}はPHP変数のため、$0はキャプチャグループです。将来は\0と記述すればもっと明確になるかもしれません。

正規表現のデモ:(例\0を使用してhttps://3v4l.org/jGZalhttps://regex101.com/r/xUvvuf/1/

あなたが取ることができる別のアプローチは、これは少し階段を下り切る、句読点を持つすべての要素を飛ばしています。

https://regex101.com/r/xUvvuf/2/

[,.;!?]<\/h[1-6]>(*SKIP)(*FAIL)|<\/h[1-6]> 

またdelimiterを変更することができます。これはもっと個人的な好みです。 /をエスケープしても構いませんが、先頭にスワップするだけでなく、/~に変更すると、それを継続できます。

デモ:https://regex101.com/r/xUvvuf/3/

preg_replace("~[^,.;!?]\K</h[1-6]>~mi" 
+1

これは良い1つのクリスです。私が欠けていると感じる唯一の点は、パターン区切り文字を '〜'に変更する助言です。パターン内のスラッシュをエスケープする必要はありません。そうでなければ、あなたはこのページから私を窒息させてしまいます。私が投稿できる貴重なものは何もありません! – mickmackusa

+0

私の質問にあなたの考えを聞きたい。ここに参加してください:https://chat.stackoverflow.com/rooms/159717/feedback-about-a-question-deleted – mickmackusa

関連する問題