【发布时间】:2011-09-25 20:20:19
【问题描述】:
我有一个动态菜单,我需要使用 CSS 类将其转换为背景图像。我想将标签转换为 css 的安全类名。
一个例子是: - 转换字符串:“产品和向日葵” - 变成一个只包含 a-z 和 1-9 的字符串。以上将被转换成一个验证字符串,可以用作类名,例如:'products_sunflowers'
【问题讨论】:
-
不知道你在这里问什么。您能否花更多时间定义问题并给出您尝试过的代码示例?
我有一个动态菜单,我需要使用 CSS 类将其转换为背景图像。我想将标签转换为 css 的安全类名。
一个例子是: - 转换字符串:“产品和向日葵” - 变成一个只包含 a-z 和 1-9 的字符串。以上将被转换成一个验证字符串,可以用作类名,例如:'products_sunflowers'
【问题讨论】:
你试过preg_replace吗?
这将为您的上述示例返回“ProductsSunflowers”。
preg_replace('#\W#g','',$className);
【讨论】:
我用这个:
preg_replace('/\W+/','',strtolower(strip_tags($className)));
它将去除除字母以外的所有内容,转换为小写并删除所有 html 标签。
【讨论】:
我写了一个示例代码来解决您的问题,希望对您有所帮助
<?php
# filename s.php
$r ='@_+(\w)@';
$a='a_bf_csdfc__dasdf';
$b= ucfirst(preg_replace_callback(
$r,
function ($matches) {
return strtoupper($matches[1]);
},
$a
));
echo $a,PHP_EOL;
echo $b,PHP_EOL;
$ php -f s.php
a_bf_csdfc__dasdf
ABfCsdfcDasdf
【讨论】:
字符串:圆顶/some.thing-to.uppercase.words
结果:DomeSomeThingToUppercaseWords
(添加你的模式)
var_dump(
str_replace(
['/', '-', '.'],
'',
ucwords(
$acceptContentType, '/-.'
)
)
);
【讨论】:
从 Drupal 7 的 drupal_clean_css_identifier() 和 drupal_html_class() 函数中无耻地插值。
/**
* Convert any random string into a classname following conventions.
*
* - preserve valid characters, numbers and unicode alphabet
* - preserve already-formatted BEM-style classnames
* - convert to lowercase
*
* @see http://getbem.com/
*/
function clean_class($identifier) {
// Convert or strip certain special characters, by convention.
$filter = [
' ' => '-',
'__' => '__', // preserve BEM-style double-underscores
'_' => '-', // otherwise, convert single underscore to dash
'/' => '-',
'[' => '-',
']' => '',
];
$identifier = strtr($identifier, $filter);
// Valid characters in a CSS identifier are:
// - the hyphen (U+002D)
// - a-z (U+0030 - U+0039)
// - A-Z (U+0041 - U+005A)
// - the underscore (U+005F)
// - 0-9 (U+0061 - U+007A)
// - ISO 10646 characters U+00A1 and higher
// We strip out any character not in the above list.
$identifier = preg_replace('/[^\\x{002D}\\x{0030}-\\x{0039}\\x{0041}-\\x{005A}\\x{005F}\\x{0061}-\\x{007A}\\x{00A1}-\\x{FFFF}]/u', '', $identifier);
// Convert everything to lower case.
return strtolower($identifier);
}
【讨论】: