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

4
  • 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? Commented Jul 1, 2022 at 17:58
  • Take a look at this suggestion: stackoverflow.com/a/3618436/1248114 Commented Jul 1, 2022 at 18:07
  • 1
    Does this answer your question? php to get all class names in css file Commented Jul 1, 2022 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. Commented Jul 1, 2022 at 18:26

2 Answers 2

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
)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.