0

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.

Pennf0lio
  • 3,888
  • 8
  • 46
  • 70

6 Answers6

2

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">   
Baba
  • 94,024
  • 28
  • 166
  • 217
1

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

Laurent Bourgault-Roy
  • 2,774
  • 1
  • 30
  • 36
1

Use trim() to strip spaces from the string.

Use str_replace() to replace spaces with another character.

Jack
  • 5,680
  • 10
  • 49
  • 74
1
strtolower(preg_replace('/\s+/','-',trim($var)));
inhan
  • 7,394
  • 2
  • 24
  • 35
  • I preferred using regex because in the case you have a string with multiple spaces (like in `etc[space][space]etc`) it considers that as a single space. – inhan Apr 25 '12 at 01:59
1

I'd go with preg_replace:

strtolower(preg_replace('_ +_', '-', $c->getCollectionName())
Sérgio Carvalho
  • 1,135
  • 1
  • 8
  • 8
0

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 ) ) , '_' ) );
}
?>
fedmich
  • 5,343
  • 3
  • 37
  • 52