Reputation: 441
I need to print an error which contain html format which in my case is <strong>
. here's my code that i want to produce the output
if (empty($namabelakang)){
$errors[] = "<strong>Nama Belakang</strong> tidak boleh kosong";
}
and here's the one which i use to print:
foreach($errors as $error){
echo clean($error)."<br>";
}
It's not print as i'm expecting, it print
<strong>Nama Belakang</strong> tidak boleh kosong
Rather than:
Nama Belakang tidak boleh kosong
Please help me how can I fix it? here's the code for clean function:
function clean($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Upvotes: 0
Views: 2616
Reputation: 307
Easy way to solve this problem is putting $error
inside "" like so:
foreach($errors as $error){
echo "$error <br>";
}
Upvotes: 0
Reputation: 441
function clean($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = str_replace(array("<strong>", "</strong>"), array("<strong>", "</strong>"), $data);
return $data;
}
Upvotes: 0
Reputation: 17071
If you want it to print as actual HTML, then you shouldn't use htmlspecialchars()
. That function will convert it to character codes that will prevent it from rendering as actual HTML.
function clean($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$str = "<strong>Nama Belakang</strong> tidak boleh kosong";
echo clean($str);
// prints out "<strong>Nama Belakang</strong> tidak boleh kosong"
What you want is to print the actual HTML. htmlspecialchars()
will convert any special characters in the string to its associated ASCII character code.
In terms of security, there isn't much of a risk when printing HTML. What's the worst that could happen? You could remove script tags beforehand, that should prevent any malicious intent.
Upvotes: 1
Reputation: 6565
Dont use the clean function....
just echo like:
foreach($errors as $error){
echo $error . "<br>";
}
there are no other functions needed.
Of course you could add the trim() like echo trim($error)
so there would be no whitespaces on beginning and end.
All other functions like htmlspecialchars
or stripslashes
will transform your string to plain text and wont let show you the html result :)
Upvotes: 0
Reputation:
foreach($errors as $error){
echo htmlspecialchars($error)."<br>";
}
Upvotes: 0