Question

I'm trying to add class name in my Concrete 5 theme. What's the elegant way to strip spaces and replace it with dashes then transform them to lower case?

I already tried lowering the case but I also need to replace the space with dashes (-)

Here's what my code look like:

<body class="<?php echo strtolower($c->getCollectionName()); echo ' '; echo strtolower($c->getCollectionTypeName()); ?>">

should look like this

<body class="home right-sidebar">

Thanks.

Was it helpful?

Solution

You can use this function ... it works with unlimited arguments

Function

<?php

function prepare() {
    $arg = func_get_args ();
    $new = array ();
    foreach ( $arg as $value ) {
        $new [] = strtolower ( str_replace ( array (
                " " 
        ), "-", $value ) );
    }
    return implode ( " ", $new );
}

?>

Usage

<body class="<?php echo prepare($c->getCollectionName(),$c->getCollectionTypeName()); ?>">

Demo

<body class="<?php echo prepare("ABC CLASS","DEF","MORE CLASSES") ?>">

Output

<body class="abc-class def more-classes">   

OTHER TIPS

Pretty easy to do :

Use $replaced = str_replace(" ", "-", $yourstring); . Replaced will have the space transformed to dash.

http://php.net/manual/en/function.str-replace.php

Use trim() to strip spaces from the string.

Use str_replace() to replace spaces with another character.

strtolower(preg_replace('/\s+/','-',trim($var)));

I'd go with preg_replace:

strtolower(preg_replace('_ +_', '-', $c->getCollectionName())

Use regular expression and replace those spaces and special characters with underscore rather than dashes

<?php
$name = '  name word _ word -  test ! php3# ';
$class_name = class_name( $name );
var_dump( $class_name );

function class_name( $name ){
    return strtolower( trim( preg_replace('@[ !#\-\@]+@i','_', trim( $name ) ) , '_' ) );
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top