0

我正在尝试在我的 Concrete 5 主题中添加类名。去除空格并用破折号替换它然后将它们转换为小写的优雅方法是什么?

我已经尝试降低外壳,但我还需要用破折号替换空格 (-)

这是我的代码的样子:

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

应该是这样的

<body class="home right-sidebar">

谢谢。

4

6 回答 6

2

你可以使用这个函数......它适用于无限的参数

功能

<?php

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

?>

用法

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

演示

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

输出

<body class="abc-class def more-classes">   
于 2012-04-25T02:00:37.653 回答
1

很容易做到:

使用$replaced = str_replace(" ", "-", $yourstring);. Replaced 会将空格转换为破折号。

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

于 2012-04-25T01:55:00.840 回答
1

使用trim()从字符串中去除空格。

使用str_replace()将空格替换为另一个字符。

于 2012-04-25T01:55:10.273 回答
1
strtolower(preg_replace('/\s+/','-',trim($var)));
于 2012-04-25T01:57:11.210 回答
1

我会选择 preg_replace:

strtolower(preg_replace('_ +_', '-', $c->getCollectionName())
于 2012-04-25T01:58:21.270 回答
0

使用正则表达式并将这些空格和特殊字符替换为下划线而不是破折号

<?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 ) ) , '_' ) );
}
?>
于 2012-04-25T02:10:17.437 回答