将字符串转换为类的安全名称

问题描述 投票:5回答:5

我有一个动态菜单,我需要使用CSS类转换为背景图像。我想将标签转换为css的安全类名。

一个例子是: - 转换字符串:'Products&Sunflowers' - 转换为仅包含a-z和1-9的字符串。以上内容将转换为可用作类名的验证字符串,例如:'products_sunflowers'

php css
5个回答
17
投票

我用这个:

preg_replace('/\W+/','',strtolower(strip_tags($className)));

它将除去所有字母,转换为小写并删除所有html标记。


4
投票

你试过preg_replace吗?

这将为您的上述示例返回“ProductsSunflowers”。

preg_replace('#\W#g','',$className);

0
投票

string:dome / some.thing-to.uppercase.words

结果:DomeSomeThingToUppercaseWords

(添加你的模式)

var_dump(
    str_replace(
        ['/', '-', '.'], 
        '', 
        ucwords(
            $acceptContentType, '/-.'
        )
    )
);

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


0
投票

BEM风格的clean_class php解决方案

从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);
}
© www.soinside.com 2019 - 2024. All rights reserved.