回答編集履歴

2

追記

2018/02/21 01:41

投稿

yambejp
yambejp

スコア114874

test CHANGED
@@ -109,3 +109,55 @@
109
109
  ```
110
110
 
111
111
  ※上記(4)はNGです
112
+
113
+
114
+
115
+ # 追記
116
+
117
+ よくよく考えたら正規表現でaタグをひろったあと
118
+
119
+ callbackの中でdom処理をしてもいいかもしれません
120
+
121
+ ```PHP
122
+
123
+ $str=<<<eof
124
+
125
+ (1)test<a href="hoge.htm">hoge1</a>test<br>
126
+
127
+ (2)test<a href="hoge.htm" target="fuga">hoge2</a>test<br>
128
+
129
+ (3)test<a href="hoge.htm" data-target="fuga">hoge3</a>test<br>
130
+
131
+ (4)test<a class="hoge target" href="hoge.htm">hoge4</a>test<br>
132
+
133
+ eof;
134
+
135
+
136
+
137
+ $pattern="/<a\s.*?</a>/";
138
+
139
+ $replacement=function($x){
140
+
141
+ $doc=new DOMDocument();
142
+
143
+ $doc->loadHTML($x[0]);
144
+
145
+ $node=$doc->getElementsByTagName("a")[0];
146
+
147
+ $target=$node->getAttribute("target");
148
+
149
+ if(empty($target)) $node->setAttribute("target","_blank");
150
+
151
+ return $doc->saveXML($node);
152
+
153
+ };
154
+
155
+ $str=preg_replace_callback($pattern,$replacement,$str);
156
+
157
+ print "<pre>";
158
+
159
+ print htmlspecialchars($str);
160
+
161
+ print "</pre>";
162
+
163
+ ```

1

参考

2018/02/21 01:41

投稿

yambejp
yambejp

スコア114874

test CHANGED
@@ -49,3 +49,63 @@
49
49
  どこまでフォローすべきかです。
50
50
 
51
51
  そういうの煩わしさを防ぐのがDOMとしての処理です
52
+
53
+
54
+
55
+ # sample
56
+
57
+ 文字列での検証は例外が多すぎるためかなり困難であることはすでにお伝えしたとおりですが
58
+
59
+ 逆に言えば極端に変なタグ設定をしていなければ以下で大丈夫だとおもいます
60
+
61
+ - まずはaタグを拾う
62
+
63
+ - aタグの中身を検証して書き換える
64
+
65
+
66
+
67
+ ```PHP
68
+
69
+ <?PHP
70
+
71
+ $str=<<<eof
72
+
73
+ (1)test<a href="hoge.htm">hoge1</a>test<br>
74
+
75
+ (2)test<a href="hoge.htm" target="fuga">hoge2</a>test<br>
76
+
77
+ (3)test<a href="hoge.htm" data-target="fuga">hoge3</a>test<br>
78
+
79
+ (4)test<a class="hoge target" href="hoge.htm">hoge4</a>test<br>
80
+
81
+ eof;
82
+
83
+
84
+
85
+ $pattern1="/(?<=<a\s).*?(?=>)/";
86
+
87
+ $replacement=function($x){
88
+
89
+ $ret=$x[0];
90
+
91
+ if(!preg_match("/(?<=\s)target/i",$x[0],$m)){
92
+
93
+ $ret.=' target="_blank"';
94
+
95
+ }
96
+
97
+ return $ret;
98
+
99
+ };
100
+
101
+ $str=preg_replace_callback($pattern1,$replacement,$str);
102
+
103
+ print "<pre>";
104
+
105
+ print htmlspecialchars($str);
106
+
107
+ print "</pre>";
108
+
109
+ ```
110
+
111
+ ※上記(4)はNGです