2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでJavaScriptのイベントハンドラを削除

Last updated at Posted at 2017-07-12
<button onclick="alert('push_button')">alert</button>

これを

<button>alert</button>

こういう風にしたい

コード

<?php
$str = '<button onClick="alert(\'push_button\')">alert</button>';

$patan = '/( | |)(onLoad|onClick|onDblClick|onBlur|onFocus|onChange|onSelect|onSelectStart|onSubmit|onReset|onAbort|onError|onLoad|onUnload|onKeyPress|onKeyDown|onKeyUp|onMouseOut|onMouseOver|onMouseDown|onMouseUp|onMousemove|onDragDrop)=("(.*?)"|\'(.*?)\')/i';

//on〇〇を削除する
$rep = preg_replace($patan,"",$str);

//削除してもまだon〇〇があるか
if(preg_match($patan,$rep)){
  //あったら、なくなるまでwhileで削除し続ける
  while (preg_match($patan,$rep)) {
    $rep = preg_replace($patan,"",$rep);
  }
  echo $rep;
} else {
  //なかったら出力
  echo $rep;
}

結果

<button>alert</button>

いい感じにできた。

追記

<button onclick=alert(1)>a</button>

このように書くと処理が実行されます...

正規表現マスターの人助けて!

2
5
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?