1

hello guyes I have CSS code and I'm trying to find a way to get only the CSS Class's name Only and clear coma and open&close tag and value and put it into an array in PHP

Example:

.dungarees {
  content: "\ef04";
}
.jacket {
  content: "\ef05";
}
.jumpsuit {
  content: "\ef06";
}
.shirt {
  content: "\ef07";
}

and I want to do a a function with PHP to convert it into an array like this

$my_array('dungarees','jacket','jumpsuit','shirt');

is there any function with php or even jquery to deal with this? thanks

  • 1
    Welcome to Stack Overflow. Do you mean to do this in PHP or in JavaScript? Are you looking to read the Class names from the CSS file itself? – Twisty Jul 01 '22 at 17:58
  • Take a look at this suggestion: https://stackoverflow.com/a/3618436/1248114 – arkascha Jul 01 '22 at 18:07
  • 1
    Does this answer your question? [php to get all class names in css file](https://stackoverflow.com/questions/39881319/php-to-get-all-class-names-in-css-file) – imvain2 Jul 01 '22 at 18:07
  • Also do you want just stand alone classes? For example, if you had `div.jacket` or `.jacket.small` Should those be included or ignored. Please provide more details about what you are trying to accomplish and what you have tried. – Twisty Jul 01 '22 at 18:26

2 Answers2

1

You can create such an array with a simple Regex.

$cssText = <<<'_CSS'
.dungarees {
  content: "\ef04";
}
.jacket {
  content: "\ef05";
}
.jumpsuit {
  content: "\ef06";
}
.shirt {
  content: "\ef07";
}
_CSS;

$matches = [];
preg_match_all('/\.([\w\-]+)/', $cssText, $matches);
$myArray = $matches[1];

print_r($myArray);

And will result in

Array
(
    [0] => dungarees
    [1] => jacket
    [2] => jumpsuit
    [3] => shirt
)
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
0

Scan the string line by line, expecting it to begin with . and end with {

<?php
$result = [];
$content_of_css = '
.dungarees {
    content: "\ef04";
  }
  .jacket {
    content: "\ef05";
  }
  .jumpsuit {
    content: "\ef06";
  }
  .shirt {
    content: "\ef07";
  }

';

// or $content_of_css = file_get_contents("path_to_css");

$arr = explode("\n", $content_of_css);
foreach ($arr as $line) {
    $line = trim($line);
    if (strrpos($line, ".") === 0) {
        $result[] = trim(substr($line, 1, strlen($line) - 2));
    }
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28