回答編集履歴

2

誤字修正。解説追加

2017/08/12 06:24

投稿

tacsheaven
tacsheaven

スコア13703

test CHANGED
@@ -14,6 +14,12 @@
14
14
 
15
15
  ```PHP
16
16
 
17
- $txt = preg_replace('/<script>[^(<\/?script>)]*</script>/', '', $html);
17
+ $txt = preg_replace('/<script>[^(<\/?script>)]*<\/script>/', '', $html);
18
18
 
19
19
  ```
20
+
21
+
22
+
23
+ [^(<\/?script>)] で、<script> ないし </script> を含まない、という条件になっています。
24
+
25
+ / は通常、preg_replace では正規表現の先頭と最後を示すキャラクターとして使われることが多いため、エスケープし て \/ と記述しています。

1

題意を間違えていたので修正

2017/08/12 06:24

投稿

tacsheaven
tacsheaven

スコア13703

test CHANGED
@@ -1,13 +1,19 @@
1
- 消したいのは <script> と </script> ですよね? <script>~</script> をまるごと消したいわけはないですよね
1
+ 消したいのは <script>~</script> ですよね
2
-
3
- であれば、「< で始まり、/ が 0もしくは1回出現し、script> で終わる」正規表現に合致するモノを消せばよいことになります。
4
2
 
5
3
 
4
+
5
+ <script>.*</script>
6
+
7
+
8
+
9
+ これだと最長一致してしまうので、<script>2</script>3<script>4</script> で一致してしまいます。
10
+
11
+ ということは、.* が **</?script> を含まない** ことを指定しなければなりません。
6
12
 
7
13
  なので、こうなります。
8
14
 
9
15
  ```PHP
10
16
 
11
- $txt = preg_replace('/<\/?script>/', '', $html);
17
+ $txt = preg_replace('/<script>[^(<\/?script>)]*</script>/', '', $html);
12
18
 
13
19
  ```