How to strip non-alphanumeric characters, convert spaces to dashes, uppercase to lowercase in this context

I am using the Advanced Custom Fields plugin, which is very good.

I am trying to take the output of one of the fields I created and give it the “permalink treatment”, that is strip out non-alphanumeric characters like slashes, convert uppercase to lowercase, and convert spaces to dashes.

Specifically I am wanting to do this with the checkbox field. I want to do this, because I want to use the outputted values as css class names.

Its output is called by this bit of PHP (modified slightly from the documented use, see example #4):

<?php

$values = get_field('field_name');
if($values)
{

foreach($values as $value)
{
    echo ' ' . $value;
}

}

?>

Which returns all of the checkbox values (5 – 10 in this case) separated by a space. I successfully got the values showing up as class names, but now I need a way to format them to actually work as class names.

How could I tweak this to work? I found this bit that seems to work for a sinlge string:

function stripJunk($string){    
    $string = str_replace(" ","-", trim($string));         
    $string = preg_replace("/[^a-zA-Z0-9-]/","", $string);
    $string = strtolower($string);
    return $string;}

but in my case it’s an array, and I don’t know how to work with that. I’m pretty worthless when it comes to PHP, except for being able to tweak things a little bit without breaking it.

1 Answer
1

You could use sanitize_html_class() or sanitize_title_with_dashes(). Both functions do almost the same. But note that much more characters a valid in CSS class names.

Examples: ✂ ✉ ✔✽ ✾ ✿ ❀ ❉ ❤ ❦ ☂ ☔ ☎ ☘ ♫ ♻ ⚥

Update

I recommend to encapsulate the code in a prefixed function to avoid collisions with poorly written plugin using the same names as you do.

Example (not tested):

function wpse_48986_custom_fields_to_classes( $field_name )
{
    $values = get_field( $field_name );

    if ( is_string( $values ) )
    {
        return trim( sanitize_html_class( $values ) );
    }

    if ( is_array( $values ) )
    {
        // Prepare the array values.
        $values = array_map( 'sanitize_html_class', $values );
        $values = array_map( 'trim', $values );
        return implode( ' ', $values );
    }

    // We didn't get a string or an array.
    return '';
}

And when you need the CSS classes somewhere just write:

print wpse_48986_custom_fields_to_classes( 'field_name' );

I couldn’t test the code code: I don’t have the plugin installed, and my main computer is broken, so there may be errors. Feel free to edit this post and fix the broken code. 🙂

Leave a Comment