2017-11-21 3 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> 

내 기능 :

$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으로 쓰면 더 명확해질 수 있습니다.

정규식 데모 : 당신은 구두점 모든 요소를 ​​건너 뛰는 걸릴 수

또 다른 방법 https://regex101.com/r/xUvvuf/1/

(. \0https://3v4l.org/jGZal를 사용 예),이 조금 단계를 줄여줍니다.

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

이것은 좋은 하나의 chris입니다. 필자가 느끼지 못한 유일한 점은 패턴 구분 기호를'~'또는 다른 것으로 변경하여 패턴 내부의 슬래시가 이스케이프 될 필요가 없다는 것입니다. 그렇지 않으면, 당신은이 페이지에서 나를 질식시킬 수 있습니다 - 제가 게시 할 수있는 가치있는 것은 없습니다! – mickmackusa

+0

내가 가진 질문에 대한 생각을 듣고 싶습니다. 여기에 가입하십시오 : https://chat.stackoverflow.com/rooms/159717/feedback-about-a-question-deleted – mickmackusa