DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

Nested To HTML Entities

A quick one:

<?php 

if(! function_exists('to_htmlentities'))
{
    function to_htmlentities(array $data)
    {
        return collect($data)
            ->map(function($value) {
                if(is_string($value)) {
                    return htmlentities($value);
                }

                if(is_array($value)) {
                    return to_htmlentities($value);
                }

                return $value;
            })
            ->toArray();
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

$data = [
    "<script>alert('hi')</script>",
    [
        "<script>alert('hello')</script>",
    ]
];

$data = to_htmlentities($data);
Enter fullscreen mode Exit fullscreen mode

This piece of code simply handle all text in array, including the nested one.

Top comments (0)