




Dans ce tutoriel HTML JavaScript, Brijesh Shah guides vous cr
Strip tag function is used to remove html tags from the string.
Here I will show you that how to use strip tag in ruby on rails, javascript and php.
#PHP:
Example 1: Remove all html tags.
1.
<?php
2.
$str
'<h1>Test1.</h1><p> text2</p>'
;
3.
echo
strip_tags
(
$str
);
4.
?>
Example 2: Allow p and h1 html tag.
1.
<?php
2.
$str
'<h1>Test1.</h1><p> text2</p>'
;
3.
echo
strip_tags
(
$str
,
"<h1><p>"
);
4.
?>
#Ruby On Rails
Example 1: Remove all html tags
#model
01.
class
User < ActiveRecord::Base
02.
include ActionView::Helpers
03.
before_save
:strip_comment
04.
def
strip_comment
05.
return
true
if
self
.comment.
nil
?
06.
self
.comment=sanitize(
self
.comment,
:tags
=>%w())
07.
save
08.
return
true
09.
end
Example 2: Allow h1 and p html tags
#model
01.
class
User < ActiveRecord::Base
02.
include ActionView::Helpers
03.
before_save
:strip_comment
04.
05.
def
strip_comment
06.
return
true
if
self
.comment.
nil
?
07.
self
.comment=sanitize(
self
.comment,
:tags
=>%w(p h1))
08.
save
09.
return
true
10.
end
#Javascript
#Add strip_tags.js
01.
function
strip_tags (str, allowed_tags) {
02.
03.
var
key =
''
, allowed =
false
;
04.
var
matches = [];
05.
var
allowed_array = [];
06.
var
allowed_tag =
''
;
07.
var
i = 0;
08.
var
k =
''
;
09.
var
html =
''
;</pre>
10.
var
replacer =
function
(search, replace, str) {
11.
return
str.split(search).join(replace);
12.
};
13.
14.
// Build allowes tags associative array
15.
if
(allowed_tags) {
16.
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
17.
}
18.
19.
str +=
''
;
20.
21.
// Match tags
22.
matches = str.match(/(<\/?[\S][^>]*>)/gi);
23.
24.
// Go through all HTML tags
25.
for
(key
in
matches) {
26.
if
(isNaN(key)) {
27.
// IE7 Hack
28.
continue
;
29.
}
30.
31.
// Save HTML tag
32.
html = matches[key].toString();
33.
34.
// Is tag not in allowed list? Remove from str!
35.
allowed =
false
;
36.
37.
// Go through all allowed tags
38.
for
(k
in
allowed_array) {
39.
// Init
40.
allowed_tag = allowed_array[k];
41.
i = -1;
42.
43.
if
(i != 0) { i = html.toLowerCase().indexOf(
'<'
+allowed_tag+
'>'
);}
44.
if
(i != 0) { i = html.toLowerCase().indexOf(
'<'
+allowed_tag+
' '
);}
45.
if
(i != 0) { i = html.toLowerCase().indexOf(
'</'
+allowed_tag) ;}
46.
47.
// Determine
48.
if
(i == 0) {
49.
allowed =
true
;
50.
break
;
51.
}
52.
}
53.
54.
if
(!allowed) {
55.
str = replacer(html,
""
, str);
// Custom replace. No regexing
56.
}
57.
}
58.
59.
return
str;
60.
61.
}
#Used strip_tags function to remove html tags.
Example 1: remove all html tags.
1.
var
html_string=
'<h1>Test1.</h1><p> text2</p>'
;
2.
var
strip_string= strip_tags(html_string);
Example 2: allow only p and h1 html tags
1.
var
html_string=
'<h1>Test1.</h1><p> text2</p>'
;
2.
var
strip_string= strip_tags(html_string,
"<p><h1>"
);