我有一个动态菜单,我需要使用CSS类转换为背景图像。我想将标签转换为css的安全类名。
一个例子是: - 转换字符串:'产品&向日葵 - 进入仅包含a-z和1-9的字符串。以上内容将转换为可用作类名的验证字符串,例如:'products_sunflowers'
答案 0 :(得分:17)
我用这个:
preg_replace('/\W+/','',strtolower(strip_tags($className)));
它将除去所有字母,转换为小写并删除所有html标记。
答案 1 :(得分:4)
您是否尝试过preg_replace
?
这将返回上面例子中的“ProductsSunflowers”。
preg_replace('#\W#g','',$className);
答案 2 :(得分:0)
我写了一个示例代码来解决您的问题,希望有所帮助
<?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
答案 3 :(得分:0)
string:dome / some.thing-to.uppercase.words
结果:DomeSomeThingToUppercaseWords
(添加你的模式)
String a = foo.getFooB().isPresent() ? foo.getFooB().get().getA() : {absolutely anything your heart desires if FooB doesn't exist};
答案 4 :(得分:0)
从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);
}