Şerit Etiketler thats [code] [/ code] segmentinde DEĞİLDİR

4 Cevap php

Ben [code] [/ code] BB stil etiketi sarılmış etiketleri dışında bir kullanıcı girilen dize etiketleri şerit için bir yol bulmaya çalışıyorum.

Örneğin, bir kullanıcı bu girebilirsiniz:

<script>alert("hacked");</script>
[code]<script>alert("hello");</script>[/code]

Ne istiyorum "kesmek" kaldırılacak uyarı, ancak "Merhaba" uyarısı olduğunu.

Ben TÜM etiketleri (php, html, css, js) [code] dışında kaldırmak ama içlerinde bir şey izin istiyorum.

Şimdiye kadar, ben istiyorum ne ters yapmak için aşağıdaki kodu var:

preg_replace('/\[code\](.*?)\[\/code\]/ise','strip_tags(\'$1\')',$code)

4 Cevap

Ben bu iyi algoritma olup olmadığından emin değilim, ama burada bir fikir.

  1. Bir diziye tüm [code] blokları kaldırmak
  2. Kalan dizgeden etiketler
  3. Önce kaldırılan [code] blokları yeniden takın.
  4. Voila!

İşte bu algo bir bıçak var

<?php

header( 'Content-Type: text/plain' );

$input = <<<BB
[code]<script>alert("hello");</script>[/code]
some text <script>alert("hacked");</script> some other text
[code]<script>alert("hello");</script>[/code]
some text <script>alert("hacked");</script> some other text
[code]<script>alert("hello");</script>[/code]
BB;

echo strip_custom( $input );

function strip_custom( $content )
{
  $pattern = "#\\[code].*?\\[/code]#i";

  if ( preg_match_all( $pattern, $content, $codeBlocks ) )
  {
    return array_join( $codeBlocks[0], array_map( 'strip_tags', preg_split( $pattern, $content ) ) );
  }
  return strip_tags( $content );
}

function array_join( array $glue, array $pieces )
{
  $glue       = array_values( $glue );
  $pieces     = array_values( $pieces );
  $piecesSize = count( $pieces );

  if ( count( $glue ) + 1 != $piecesSize )
  {
    return false;
  }

  $joined = array();
  for ( $i = 0; $i < $piecesSize; $i++ )
  {
    $joined[] = $pieces[$i];
    if ( isset( $glue[$i] ) )
    {
      $joined[] = $glue[$i];
    }
  }
  return implode( '', $joined );
}

Düzenli ifadeler ideal değildir yerdir. Eğer "ne want" değil "ne don't istiyoruz" biliyorum düzenli ifadeler mükemmel. Benim önerim aynı şeyi yapıyor alternatif bir yol bulmaya çalışın olduğunu, ancak düzenli ifadeler olmadan.

Bu iş için bir HTML Parser kullanmak istiyorum.

Ben PHP bilmiyorum ama Google, bu HTML Parser for PHP bulundu.

Bu gibi basit bir ayrıştırıcı kullanın:

stack-pointer = 0
while not finished:
    stack-pointer-n = code-start-matched or endl
    tag-free-str = regex-magic-to-strip-tags(extract-str(stack-pointer, stack-pointer-n))
    preserve-str = extract-str(stack-pointer-n, code-endl-matched or endl)
    stack-pointer = code-endl-matched + 1
    push(tag-free-str)
    push(preserve-str)