Home » Php » php – Convert string to safe name for class

php – Convert string to safe name for class

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a dynamic menu that I need to convert into background images using CSS classes. I would like to convert the label into a safe class name for the css.

An example being:
– Convert string: ‘Products & Sunflowers’
– Into a string that contains only a-z and 1-9. The above would be converted into a validate string that can be used as a class name eg: ‘products_sunflowers’

How to&Answers:

I use this:

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

It will strip all but letters, convert to lower-case and remove all html tags.

Answer:

Have you tried preg_replace?

This will return ‘ProductsSunflowers’ for your above example.

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

Answer:

BEM-style clean_class php solution

Shamelessly interpolated from Drupal 7’s drupal_clean_css_identifier() and drupal_html_class() functions.

/**
 * 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);
}

Answer:

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

result: DomeSomeThingToUppercaseWords

(add your pattern ofc)

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

Answer:

I wrote a sample code to solve your problem, hope it helps

<?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